I’m using WCF Dataservice / EF 4.1 and a WPF Client application.
Here is my problem in a simpler form. Lets say I query clients:
var query = (from o in ServiceRef.Clients.Expand("Addresses,PhoneNumbers,EmailAddresses")
where o.FirstName.ToLower().Contains(sf) ||
o.LastName.ToLower().Contains(sf) || ...
orderby o.LastName
select o).Take(100);
This is all I need to identity a client. However, down the road I mite want to see the Comments, purchase history or other related entities not “Expanded” in the first query. If I query again, using the same ServiceRef Context, I will never get “Comments” expanded.
I’m guessing this has to do with the Context finding the ‘Client’ entity is already tracked and therefor not executing the new query against the Service.
Now some posts say, one should never keep a DBContext around that long, which I don’t agree up on Completely. It’s a simple Master/Details scenario. Creating a new context for every ‘Details Query’ to get the additional data seems somehow wrong. Is there a way to force EF to “reload” an entity to get additional data?
I can, of course, expand every attached entity I ever need in the initial query. But then I xfer a massive amount of data for each search result. 95% of which will never ever be used.
To be clear. What I am asking for is more of a ‘best practice’ question. Is there a way in the middle? Between Expanding (…) all data all the time <> Creating new Context all the time.? Is there a way to load additional data if needed.
Thanx, Andreas
Your question has two parts.
How to get additional data?
ServiceRef.Clients.Expand("Comments")in your initial query but it is obviously something you don’t want – this is called eager loadingServiceRef.LoadProperty(client, "Comments")to populate comments just for single client – this can be called explicit loadingHow long should context be alive?
It depends. Correct approach is indeed to keep the context alive as short as possible but it doesn’t mean to close context after each operation. Context should be used as unit of work and all related operations should be operated on the same context instance. In case of WPF / WinForm application it means that context can indeed live for a longer period of time – it is usually paired with some form / presenter / etc. You should not use same context among multiple forms which are not related and don’t form single unit of work / logical operation (objects in the same unit of work are operated and saved together).