我有嵌套集合一个实体如下更新断开连接的对象图
public class Profile
{
[Required]
public String Id { get; set; }
public String Name { get; set; }
public virtual ICollection<Plugin> Plugins { get; set; }
}
public class Plugin
{
[Required]
public int Id { get; set; }
public String Name { get; set; }
public virtual ICollection<Counter> Counters{ get; set; }
}
public class Counter
{
[Required]
public int Id { get; set; }
public int SomeVal { get; set; }
}
我想开发一个程序(即给出一个配置文件列表时)插入/更新/删除整个嵌套的对象图
即基本上我想要做删除更新和插入,情景模式,插件和柜台,适用于我可以
由于型材的新断开的列表(NewProfiles)和一个clientId最简单,最有效的方式
using (var dc = new JCEContext())
{
var existingProfiles = dc.Profiles.AsNoTracking().Where(x => Id == ClientId).ToList();
var addedProfiles = NewProfiles.Except(existingProfiles, x => x.Id).ToList();
var deletedTeachers = existingProfiles.Except(Profiles, x => x.Id);
var modifiedProfiles = dcmProfiles.Except(addedProfiles, x => x.Id);
addedProfiles.ToList().ForEach(tchr => dc.Entry(tchr).State = EntityState.Added);
deletedTeachers.ToList().ForEach(tchr => dc.Entry(tchr).State = EntityState.Deleted);
foreach (var profile in modifiedProfiles)
{
var entity = dc.Profiles.Find(profile.Id);
if (entity == null)
continue;
var entry = dc.Entry(entity);
entry.CurrentValues.SetValues(profile);
}
dc.SaveChanges();
}
助手功能
public static IEnumerable<T> Except<T, TKey>(this IEnumerable<T> items, IEnumerable<T> other,Func<T, TKey> getKey)
{
return from item in items
join otherItem in other on getKey(item)
equals getKey(otherItem) into tempItems
from temp in tempItems.DefaultIfEmpty()
where ReferenceEquals(null, temp) || temp.Equals(default(T))
select item;
}
上述程序将只更新顶级对象
我将如何去运用我这里有逻辑,对象图的休息吗?即插入更新和删除插件以及相关的计数器?
注意:多数这段代码的某处发现我已经适应
GraphDiff是这个工具。 –
我已经看过,但是我无法完全弄清楚如何让它工作,没有很多从地面零开始的人的文档,是否有可能发布一个示例代码的答案那是我需要的球的一部分? –
我在StackOverflow中看到过示例代码,请在Google中尝试“site:stackoverflow.com GraphDiff”。 –