I have two classes:
public class Foo
{
public int FooId {get;set;}
public virtual ICollection Bars {get;set;}
}
public class Bar
{
pu
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.
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.
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();
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();