我有嵌套集合一個實體如下更新斷開連接的對象圖
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」。 –