开发者

Linq to Sql object not populated

I am new to Linq and am struggling with what I think is a deferred execution problem. I have a data layer in my application which uses Linq to Sql and then passes the entity through to the viewmodel using a WCF service (MVVM architecture). The object gets serialised at this point.

I am passing thorough an Employee object which should have a child Rota object however when I try to access it in my view model from the WCF, Rota is null. If I view the employee object in debug prior to it being passed t开发者_StackOverflow社区hrough then the Rota gets serialised and is available in my View Model. My Linq query is a simple select, how do I make it pass through the rota? I could loop through each employee in order to enumerate the query and rota object but this feels very wrong.


Since you're using LinqToSql, you should use DataContext.LoadWith when you fetch your objects. This is the preferred way of telling LinqToSql what it should pull down (since it defaults to lazy load).

DataLoadOptions options = new DataLoadOptions();
options.LoadWith((Employee c) => c.Rota);
db.LoadOptions = options;

http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.loadwith.aspx

This has the benefit of being far more efficient on the SQL-side when compared with calling ToList or expanding EntityRef properties individually.


I assume Rota is contained in a collection. Set the collection type as List<Rota>, this should work if this is the case.


You are on the right track already - the query only gets executed once you iterate it (inspecting it in debug mode causes this iteration as well). Just call ToList() on the IQueryable (thus iterating it) before sending it through the web service.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜