EF Inserting Duplicate Parent Objects

前端 未结 4 1660
别跟我提以往
别跟我提以往 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:38

    Try

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

    It seems like the entity key isn't being set uniquely when assignment occurs before the entity is added to the context.

    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2021-01-13 02:48

    Not sure if this is the best practice, but when I ran into this issue I ended up setting the parent entity to Null but maintain any FK reference, this stopped the parent entity from being inserted on child entities:

    var bar = new Bar();
    context.Bars.Add(bar);
    bar.Foo == null;
    bar.FooId = existingFooParent.Id;
    context.SaveChanges();
    
    0 讨论(0)
  • 2021-01-13 02:54

    I think that you are approaching the problem in the wrong way. You want to add the new Bar object to your existing foo object instead of the other way round:

    var foo = from f in context.Foos
              where f.FooId == 1
              select f;
    
    var bar = new Bar();
    foo.Bars.Add(bar);
    
    context.SaveChanges();
    
    0 讨论(0)
提交回复
热议问题