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 foo with the same context as adding the new bar with the related foo won'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 foo is an IQueryable<Foo> and not a Foo) is to materialize the foo, for example:
var foo = (from f in context.Foos
where f.FooId == 1
select f).Single();
Other than that the code snippet is fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With