简体   繁体   English

禁用延迟加载实体框架导航属性

[英]Disable Lazy-Load Entity Framework Navigation Properties

Question

Is there any way to make it so that an entity returned from a DbContext query returns null (or some other specific value) when you try to access a navigation property that you did not specificly .Include()? 是否有任何方法可以使当尝试访问未明确包含.include()的导航属性时,从DbContext查询返回的实体返回null(或其他特定值)? For example: 例如:

var parents = dbContext.People.Where(p => p.Children.Any()).Include("Children").ToList();
//Assert all parents have children...
Assert.IsTrue(parents[0].Children.Any());

And... 和...

var parents = dbContext.People.Where(p => p.Children.Any()).ToList();
//Assert all children collections are null... NOT LAZY LOADED
Assert.IsTrue(parents[0].Children == null);

To be clear, I do not want the property to be Eager-Loaded. 需要明确的是,我不希望该属性被急切加载。 I don't want it to be loaded at all. 我根本不希望加载它。 I've tried Detaching the entity from the context, but this doesn't help. 我尝试过从上下文中分离实体,但这无济于事。

Background 背景

The reason I am trying to do this is because i need to access the entity object on a diffrent thread than the one the DbContext was created on. 我尝试执行此操作的原因是,我需要在与创建DbContext的线程不同的线程上访问实体对象。 Because of this, I do NOT want the navigation property to be set to some defered excution linq statement. 因此,我不希望将Navigation属性设置为某些延迟执行linq语句。 The problem is that since I cannot access DbContext to check if a navigation property is loaded or not (due to it not being thread safe) I have no way of knowing if I need to create a new DbContext on the current thread to retrieve the missing data. 问题是,由于我无法访问DbContext以检查导航属性是否已加载(由于它不是线程安全的),因此我无法知道是否需要在当前线程上创建新的DbContext来检索丢失的属性数据。 This is the same problem that I was trying to solve with How to tell if a Navigation Property is loaded without DbContext 这是我试图解决的相同问题,即如何确定是否在没有DbContext的情况下加载了导航属性

Update 更新资料

Setting the DbContext's Configuration.LazyLoadingEnabled property to false prevents the linq from getting auto-wired up, but for navigation properties that are collections this results in a empty collection rather than null. 将DbContext的Configuration.LazyLoadingEnabled属性设置为false可以防止linq自动连接,但是对于作为集合的导航属性,这将导致一个空集合而不是null。

To solve the collection based problem, I Modified my T4 template to generate an empty default constructor rather than one that set each ICollection equal to an empty HashSet. 为了解决基于集合的问题,我修改了T4模板以生成一个空的默认构造函数,而不是将每个ICollection设置为一个空HashSet的默认构造函数。

You can enable / disable lazy-loading by setting the Configuration.LazyLoadingEnabled property of your DbContext 您可以通过设置DbContextConfiguration.LazyLoadingEnabled属性来启用/禁用延迟加载

context.Configuration.LazyLoadingEnabled = false;
var parents = dbContext.People.Where(p => p.Children.Any()).ToList();
context.Configuration.LazyLoadingEnabled = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM