Entity framework lazyloading为false时,即时加载不起作用
我有一个数据库第一应用程序,其中包含实体Entity framework lazyloading为false时,即时加载不起作用,entity-framework,entity-framework-6,entity-framework-5,lazy-loading,eager-loading,Entity Framework,Entity Framework 6,Entity Framework 5,Lazy Loading,Eager Loading,我有一个数据库第一应用程序,其中包含实体促销和产品,以及导航属性促销。产品。促销中还有其他导航属性。我想在我的一个方法中忽略这些其他导航属性,只加载促销,每个促销都有一个产品集合(下面的代码被简化) 如果我使用延迟加载: // Lazy Loading true by default // ctx.ObjectContext.ContextOptions.LazyLoadingEnabled = false; var data = from p in ctx.ObjectContext.Prom
促销
和产品
,以及导航属性促销。产品
。促销中还有其他导航属性。我想在我的一个方法中忽略这些其他导航属性,只加载促销,每个促销都有一个产品集合(下面的代码被简化)
如果我使用延迟加载:
// Lazy Loading true by default
// ctx.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
var data = from p in ctx.ObjectContext.Promotions select p;
data.First().Products包含1个产品
如果我使用即时加载:
ctx.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
var data = from p in ctx.ObjectContext.Promotions.Include(p => p.Products)
select p;
data.First().Products为空
我曾成功地在其他地方使用过。我不知道为什么这里对我不起作用
我意识到我可以简单地使用linq连接来获得所需的结果,但这将使我的类复杂化,并导致一些重复的代码。我还可以使用以下命令强制执行:
ctx.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
var data = from p in ctx.ObjectContext.Promotions
select new {
Promo = p,
Products = p.Products
};
这在data.First().Promo.Products
或data.First().Products
中给出了1项,但我更愿意“按书”来做
实体代码
public static Promotion CreatePromotion(global::System.Int32 id, ...)
{
Promotion promotion = new Promotion();
promotion.Id = id;
...
return promotion;
}
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute(“MyDataModel”、“PromotionsProducts”、“Product”)]
公共实体收集产品
{
得到
{
返回((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection(“MyDataModel.PromotionsProducts”,“Product”);
}
设置
{
如果((值!=null))
{
((IEntityWithRelationships)this.RelationshipManager.InitializeRelatedCollection(“MyDataModel.PromotionsProducts”、“Product”、value);
}
}
}
这里肯定还有其他原因,因为我在本地进行了测试,它可以与LazyLoadingEnabled=false
和Include(p=>p.Products)
一起工作。你需要检查其余的代码。我对这里发生的事情有强烈的怀疑,但我真的需要看看完整的类定义。@GertArnold我会尝试去理解,但需要稍微精简一下。同时,告诉我你的怀疑,我可以运行一些测试。好的,我对构造函数特别感兴趣。它可能是。它首先是数据库,所以我的实体是自动生成的,所以没有提升构造函数。有一个createpromotionfactory方法。我已经在上面和PromotionsProducts导航属性一起发布了。也许我的外键坏了。
[XmlIgnoreAttribute()]
[SoapIgnoreAttribute()]
[DataMemberAttribute()]
[EdmRelationshipNavigationPropertyAttribute("MyDataModel", "PromotionsProducts", "Product")]
public EntityCollection<Product> Products
{
get
{
return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Product>("MyDataModel.PromotionsProducts", "Product");
}
set
{
if ((value != null))
{
((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Product>("MyDataModel.PromotionsProducts", "Product", value);
}
}
}