开发者

How do I avoid immediate loading of associated data in Linq to SQL

开发者 https://www.devze.com 2022-12-12 10:49 出处:网络
Say I have an entity that looks as follows public Order OrderEntity { EntityRef<Customer> CustomerEntity;

Say I have an entity that looks as follows

public Order OrderEntity 
{      
   EntityRef<Customer> CustomerEntity;      
   EntitySet<OrderDetail> OrderDetailEntity;      
   ...      
   ...
}

When I retrieve an OrderEntity, and convert it say to a List, L2S, will also retrieve the enti开发者_开发问答ty in CustomerEntity and all the entities in OrderDetailEntity (plus all their child entities etc.). Often times we do not want this behavior. How to tell L2S not to do this?

Thanks - Randy


After creating your data context set deferred loading to be enabled.

dataContext.DeferredLoadingEnabled = true;

When the code accesses one of these relationships, null is returned if the relationship is one-to-one, and an empty collection is returned if it is one-to-many. The relationships can still be filled by setting the LoadOptions property.

The main scenario for this property is to enable you to extract a piece of the object model and send it out (for example, to a Web service).

See the other remarks for interaction with object tracking.


re: the EntitySet, LINQ-to-SQL will only lazy-load those entities.

To prove this, retrieve our OrderEntity and then dispose of your data context. You will get an except saying that you can't retrieve more data from a disposed context.

You can force LINQ-to-SQL to load these child entities using the LoadOptions class, but you can't force it not to load them. By default they are not loaded.

I am not aware if you can remove the reference to the parent entity.


Lazy loading of EntityRefs/Sets is the default L2S behavior.

One thing that might make you think otherwise, is that watching your instance in the Visual Studio debugger accesses the ref'd properties, causing them to be loaded. This might make it seem like that they're being eagerly loaded, when in reality it's just VS.

To see exactly what's being loaded and when, set your context's Log property to Console.Out. This will output any executed commands into the Visual Studio output window.

0

精彩评论

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