简体   繁体   中英

EF many to many one way add same item twice to child collection doesn't get saved

Thx for taking the time to read this. I've been looking for an answer to this problem for a week already and I'm running out of ideas... This is the scenario:

The model:

public class Parent{
    public Guid Id {get;set;}
    public virtual ICollection<Child> ChildCollection{ get; set; }
}

public class Child {
    public Guid Id {get;set;}
    public string Name{get;set}
}

On Model creating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Parent>()
            .HasMany(c => c.ChildCollection)
            .WithMany()
            .Map(x =>
            {
                x.ToTable("ParentToChildMapping");
                x.MapLeftKey("ParentId");
                x.MapRightKey("ChildId");
            }); 
}

Now the problem:

If I have a Parent object with a Child object in the collection and try to add a new object of same id to the child collection the DbContext doesn't "detect" the change and doesn't add a new entry in the mapping table. But if I add a new Child (that doesn't exist in the collection) it does get added ok.

For Example:

{  
   var childId = Guid.Parse("cbd5bccc-b977-4861-870d-089994958cdf");
   var parent = new Parent { ChildCollection = new HashSet<Child>() };
   var context = new DBContext();
   var child = context.Childs.Single(c=>c.Id=childId);

   parent.ChildCollection.Add(child);
   context.Parents.Add(parent);
   context.SaveChanges();
}

Then:

{
   var childId = Guid.Parse("cbd5bccc-b977-4861-870d-089994958cdf");
   var context = new DBContext();
   var parent = dbContext.Parents.Include(p=>p.ChildCollection).Single(p=>p.Id=parentId); // The id saved in the point before.
   var child = context.Childs.Single(c=>c.Id=childId);

   parent.ChildCollection.Add(child);
   // At this point parent.ChildCollection.Count() = 2
   context.SaveChanges();
}       

The count of the collection is 2, which is fine. But save changes doesn't add the item. If I retrieve it back from the db using context again, it only returns 1 element in the collection.

Any thoughts are wellcome.

You're trying to add the same child to a parent twice , and this won't work. If you were successful, you would end up with something like the following in the database:

  • one Child, Id = "cbd5bccc-b977-4861-870d-089994958cdf"
  • one Parent, Id = "the-parent-id"
  • two ParentToChildMappings, both had ParentId = "the-parent-id" and ChildId = "cbd5bccc-b977-4861-870d-089994958cdf"

which is not allowed for a relational database, because (ParentId, ChildId) is the primary key of ParentToChildMapping, and two rows in a table cannot have the same primary key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM