On the problem that many to many relational tables cannot be updated and inserted

  • 2021-08-12 02:26:54
  • OfStack

In EF, When we design the model, Will design a many-to-many relationship, In EF, this relationship will be transformed into two 1-to-many relational tables. This is more friendly, Because many to many, It doesn't mean much to the business itself, So hiding, no harm, but for this hiding, for developers, you can't take the initiative to control this relational table, and need to use EF's update to update the main table while updating the relational table, which will have some problems for beginners. Today, we are talking about the problem that many-to-many relationships cannot be updated and inserted.

Data structure


public partial class WebManageRoles : Lind.DDD.Domain.Entity
{
public WebManageRoles()
{
this.WebManageMenus = new List<WebManageMenus>();
this.WebManageUsers = new List<WebManageUsers>();
}
[DisplayName(" Name "), Required]
public string RoleName { get; set; }
[DisplayName(" About ")]
public string About { get; set; }
[DisplayName(" Sort "), Required]
public int SortNumber { get; set; }
[DisplayName(" Last operator ")]
public string Operator { get; set; }
[DisplayName(" Authority "), Required]
public int OperatorAuthority { get; set; }
[DisplayName(" Department "), Required]
public int DepartmentID { get; set; }
public virtual WebDepartments WebDepartments { get; set; }
public virtual ICollection<WebManageMenus> WebManageMenus { get; set; }
public virtual ICollection<WebManageUsers> WebManageUsers { get; set; }
}

About AutoDetectChangesEnabled

Reference: https://msdn.microsoft.com/en-us/data/jj556205.aspx

Uncle's explanation, when AutoDetectChangesEnabled is true, you can load dependency relationship, when inserting and updating will be completed synchronously (many-to-many, 1-to-many relationship used), when the value is false, only update (insert) the data of the main table

Problem solving


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);

Settings in the Data Context


public ManagerContext()
: base("DefaultConnection")
{
this.Configuration.AutoDetectChangesEnabled = true;// Many to many, 1 Multiple progresses curd Operation requires the true
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;// Prohibit dynamic interception System.Data.Entity.DynamicProxies.
}

Related articles: