Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Inserting Duplicate Parent Objects

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.

like image 309
mattdwen Avatar asked Nov 06 '22 02:11

mattdwen


1 Answers

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.

like image 120
Slauma Avatar answered Nov 26 '22 10:11

Slauma