views:

47

answers:

3

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 through 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.

A: 

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

Bablo
A: 

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.

Femaref
+2  A: 

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.

Kirk Woll
Exactly what I had just started reading about - I'm slowly coming round to this Linq thing!
Macros