0

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.

Anibal
  • 3
  • 1

1 Answers1

0

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.

ycsun
  • 1,825
  • 1
  • 13
  • 21
  • I see what u mean, I'll create a new entity to hold both ids plus a primary key. I was afraid that was going to be the answer. Thx – Anibal Dec 10 '15 at 11:01