开发者

Problem regarding Entity Framework

I am just getting started with Entity Framework. Th开发者_StackOverflowe problem i face is since it is an ORM it models everything as real world entities. Hence, if i fetch a parent record it's child records are fetched automatically. If i have 1000's of child records all of them get fetched even though i may not need them currently. This i think is very inefficient.

You would argue to use Lazy Loading in Linq and thus solve problem so that sql doesn't get sent to the SQL Server until it is accessed. But what if i am working in a web service or WCF based environment. In web services we see request response model. And as i know we can't use Lazy loading in web services because web services aren't going to be called on the fly when you access that property :d.

Say i have order and orderDetails table. In some scenarios I want orderDetails as soon as I fetch order and in others I do not want orderdetails.

I never faced this problem using stored procedures. But since Linq is standard for querying any data I am getting my hands on it.

So, how do I solve this problem?

Thanks in advance :)


First of all, even with Entity Framework, you can totally use stored procedures to do your querying - no problem there.

Next - if you sometimes need the order details with your Order, and sometimes you don't - have some parameter specify this - something like:

[OperationContract]
Order FetchOrder(int OrderID, int numDetails);

If numDetails = 0, you don't fetch any details and don't return any details - if you have numDetails = 10, you fetch and return the first ten order details. You can definitely do this in Linq-to-Entities.

In that case, you'd probably also have to have some kind of an operation to fetch more details, if needed.

I don't think there's any architectural problem here - you just need to rethink and possibly rework your own service contracts to handle that scenario of sometimes loading details, and sometimes not.


There are a couple of ways to implement prefetching (loading up front).

Read up on ADO .NET Data Services and specifically its support as an IExpandProvider (which allows you to specify what related entities you want to fetch upfront to send back to your WCF client): http://msdn.microsoft.com/en-us/library/cc907912.aspx

If you REALLY want to go the lazy loading route (even in a remote client scenario), I've implemented this in the past by using Castle or Unity (mocking frameworks would work too) to create dynamic proxies that override the properties on my entity and, if they're being used in a remote scenario, actually accessing the property makes a subsequent WCF call to go out and fetch the related entity(ies). This has a pretty big performance impact though because of the multiple remote calls, and I avoid using this functionality except when dealing with dynamically compiled code snippets.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜