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