DBContext lazyloadingenabled设置为true仍默认加载相关实体
LazyLoadingEnabled专门设置为true以防止相关实体在我正在使用的上下文中加载。
药物类别中有药物相关对象列表。
public class Drug { public virtual List DrugIdentities { get; set; } }
如果我想要包含要加载的相关实体,则类的特定配置设置密钥和hasmany关系。
public DrugConfiguration() { this.HasKey(d => d.DrugID); this.HasMany(d => d.DrugIdentities).WithOptional(d => d.Drug).Map(d => d.MapKey("DrugID")); }
当使用linq查询加载Drug上下文时,对象显示它不包含相关的DrugIdentities。
context.Configuration.LazyLoadingEnabled = true; var drugs = from d in context.Drug where d.Active == true select d;
药物[0]。药物身份数= 1
我希望药物[0] .DrugIdentities等于NULL,因为lazyloading设置为true?
要禁用延迟加载,请将LazyLoadingEnabled设置为false而不是true。 请参阅中的Lazy,Eager和Explicit Loading of Related Data
如果要设置ProxyCreationEnabled = false
则必须专门设置ProxyCreationEnabled = false
。
测试通过了我的预期。 第一个查询返回Drugs
对象,而DrugEntities
返回NULL
。 第二个查询返回DrugEntities
因为我使用Include
进行DrugEntities
加载。
var queryDrug = from d in context.Drug where d.Active == true select d; var drugresults = from d in context.Drug.Include(e => e.DrugIdentities) where d.Active == true select d;
这是延迟加载的行为。 如果你只是使用药物的属性,那么就不会有任何sql来查询DrugIdentities。 如果您使用DrugIdentities甚至只是在调试窗口中观察它,那么将有sql查询DrugIdentities和每种药物的单一DrugIdentities搜索查询。 您可以通过查看SQL事件探查器捕获的SQL来certificate该行为。 如果您想在查询药物时使DrugIdentities为空,您可以通过删除DrugIdentities之前的虚拟关键词来更改模型。 然后,当您查询药物时,DrugIdentities将保持为空,直到您通过另一个查询将DrugIdentities加载到上下文。