在EF里,我們?cè)O(shè)計(jì)模型時(shí),會(huì)設(shè)計(jì)到多對(duì)多關(guān)系,在EF里會(huì)把這種關(guān)系會(huì)轉(zhuǎn)成兩個(gè)一對(duì)多的關(guān)系表,這是比較友好的,因?yàn)槎鄬?duì)多來(lái)說(shuō),對(duì)于業(yè)務(wù)本身沒(méi)什么意思,所以隱藏了,沒(méi)什么壞處,但對(duì)于這個(gè)隱藏來(lái)說(shuō),對(duì)開(kāi)發(fā)人員來(lái)講你就無(wú)法主動(dòng)控制這張關(guān)系表了,而需要使用EF的update來(lái)更新主表的同時(shí)去更新關(guān)系表,這對(duì)于初學(xué)者會(huì)出現(xiàn)一些問(wèn)題,今天說(shuō)的就是多對(duì)多關(guān)系無(wú)法更新和插入的問(wèn)題.
數(shù)據(jù)結(jié)構(gòu)
public partial class WebManageRoles : Lind.DDD.Domain.Entity
{
public WebManageRoles()
{
this.WebManageMenus = new ListWebManageMenus>();
this.WebManageUsers = new ListWebManageUsers>();
}
[DisplayName("名稱"), Required]
public string RoleName { get; set; }
[DisplayName("關(guān)于")]
public string About { get; set; }
[DisplayName("排序"), Required]
public int SortNumber { get; set; }
[DisplayName("最后操作人")]
public string Operator { get; set; }
[DisplayName("權(quán)限"), Required]
public int OperatorAuthority { get; set; }
[DisplayName("部門"), Required]
public int DepartmentID { get; set; }
public virtual WebDepartments WebDepartments { get; set; }
public virtual ICollectionWebManageMenus> WebManageMenus { get; set; }
public virtual ICollectionWebManageUsers> WebManageUsers { get; set; }
}
關(guān)于AutoDetectChangesEnabled
參考:https://msdn.microsoft.com/en-us/data/jj556205.aspx
大叔的解釋,當(dāng)AutoDetectChangesEnabled為true時(shí),可以加載依賴的關(guān)系,在插入和更新時(shí)會(huì)有同步完成(多對(duì)多,一對(duì)多關(guān)系時(shí)使用),當(dāng)值為false時(shí),只更新(插入)主表的數(shù)據(jù)
問(wèn)題解決
old.WebManageMenus = menuRepository.GetModel(i => menu.Contains(i.Id)).ToList();
old.DepartmentID = dept;
old.RoleName = entity.RoleName;
old.SortNumber = entity.SortNumber;
old.About = entity.About;
old.DataUpdateDateTime = DateTime.Now;
roleRepository.Update(old);
在數(shù)據(jù)上下文中的設(shè)置
public ManagerContext()
: base("DefaultConnection")
{
this.Configuration.AutoDetectChangesEnabled = true;//對(duì)多對(duì)多,一對(duì)多進(jìn)行curd操作時(shí)需要為true
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;//禁止動(dòng)態(tài)攔截System.Data.Entity.DynamicProxies.
}
以上所述是小編給大家介紹的關(guān)于多對(duì)多關(guān)系表無(wú)法更新與插入的問(wèn)題 ,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
您可能感興趣的文章:- 數(shù)據(jù)庫(kù)修改多對(duì)多的中間表的記錄的技巧