Reputation: 4914
Let's say I have an entity Foo.
public class Foo
{
public int Id {get;set;}
public virtual ICollection<Bar> Bars {get;set;}
}
When I get this entity from the db then I actually get a proxy and everything works as it should be.
But, can I attach Foo to DbContext and create the proxy manually so Bars would not return null after attaching it, but an actual collection of bars?
Meaning
var foo = new Foo { Id = 1 };
Context.Set<Foo>().Attach(foo);
foo = CreateProxyOf(foo);
var countOfBars = foo.Bars.Count();
Is there something like CreateProxyOf?
Upvotes: 4
Views: 1331
Reputation: 3126
When you get all Foos or a single Foo you can tell EF to get bars at the same time. For example:
var foos = db.Foos.Include("Bars");
var foo = db.Foos.Include("Bars").Single(f => f.Id == 1);
More details on MSDN here
http://msdn.microsoft.com/en-us/library/bb896272.aspx
Upvotes: 0
Reputation: 364259
Yes there is a way but instead of Foo's constructor you must use:
var set = Context.Set<Foo>();
var foo = set.Create();
foo.Id = 1;
set.Attach(foo);
var countOfBars = foo.Bars.Count();
Upvotes: 6