EF Insert Duplicate Parents

I have two classes:

public class Foo { public int FooId {get;set;} public virtual ICollection<Bar> Bars {get;set;} } public class Bar { public int BarId {get;set;} public virtual Foo {get;set;} } 

If I run the following code, I get Foreign Key Conflict in FooId.

 var foo = from f in context.Foos where f.FooId == 1 select f; var bar = new Bar(); bar.Foo = foo; context.Bars.Add(bar); context.SaveChanges(); 

If I turn off all key checks in SQL, I get a duplicate of Foo in the database.

+4
source share
4 answers

Loading foo using the same context , since adding a new bar with the corresponding foo will not lead to duplication. I assume that your real code uses two different contexts.

The only thing that needs to be changed in the code (which will not compile since foo is IQueryable<Foo> and not foo ) should materialize foo , for example:

 var foo = (from f in context.Foos where f.FooId == 1 select f).Single(); 

In addition, the code snippet is fine.

+1
source

I think that you are approaching the problem wrong. You want to add a new Bar object to an existing foo object, and not vice versa:

 var foo = from f in context.Foos where f.FooId == 1 select f; var bar = new Bar(); foo.Bars.Add(bar); context.SaveChanges(); 
+1
source

Try

 var bar = new Bar(); context.Bars.Add(bar); bar.Foo == foo; context.SaveChanges(); 

It seems that the key of the object is not set unambiguously when assignment occurs before the object is added to the context.

0
source

Not sure if this is the best practice, but when I ran into this problem, I ended up setting the parent to Null, but kept any FK reference, this stopped the parent from pasting to child objects:

 var bar = new Bar(); context.Bars.Add(bar); bar.Foo == null; bar.FooId = existingFooParent.Id; context.SaveChanges(); 
0
source

Source: https://habr.com/ru/post/1340249/


All Articles