EF Inserting Duplicate Parent Objects

前端 未结 4 1695
别跟我提以往
别跟我提以往 2021-01-13 02:29

I have two classes:

public class Foo
{
    public int FooId {get;set;}
    public virtual ICollection Bars {get;set;}
}

public class Bar
{
    pu         


        
4条回答
  •  天命终不由人
    2021-01-13 02:48

    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 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.

提交回复
热议问题