EF Inserting Duplicate Parent Objects

前端 未结 4 1687
别跟我提以往
别跟我提以往 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: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();
    

提交回复
热议问题