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 a Foreign Key Conflict on 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 disable all the key checks in SQL, I end up with a duplicate Foo in the database.
Loading the
foowith the same context as adding the newbarwith the relatedfoowon’t cause a duplication. My guess is that your real code uses two different contexts.The only thing to change in the code (which won’t compile because
foois anIQueryable<Foo>and not aFoo) is to materialize thefoo, for example:Other than that the code snippet is fine.