Answer the question
In order to leave comments, you need to log in
How to correctly update the collection of "children" in Entity Frameword 6?
There is a classParent
public class Parent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
public ICollection<Child> Children{ get; set; }
}
Child
public class Child
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int? Id { get; set; }
[ForeignKey(nameof(Parent))]
public int ParentId{ get; set; }
public virtual Parent Parent{ get; set; }
}
var children = ChildrenDTO.Select(mapper.Map<Child>);
using (var dbContext= new AppDbContext())
{
var pulledParent = quoteMonkeyDbContext.Parents
.Include(rp => rp.Children)
.First(rp => rp.Id == Parent.Id);
pulledParent .Children= children .ToList();
dbContext.SaveChanges();
}
System.InvalidOperationException: Multiplicity constraint violated. The role 'Child_Parent_Target' of the relationship 'MyAssembly.Persistence.Child_Parent' has multiplicity 1 or 0..1.
Answer the question
In order to leave comments, you need to log in
EntityFramework has a change tracker that keeps track of the state of entities in order to understand what to do with them when updated. In your case, all your mapped objects end up in the Added state. So EF tries to insert them. You need to exclude from your collection objects with identifiers that already exist in the database and insert only those that do not exist.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question