[英]Entity framework - displaing related entities without include
I am developing code first EF6 application and I have one problem with including related entities. 我正在开发第一个代码EF6应用程序,并且在包含相关实体时遇到一个问题。
I have model like this: 我有这样的模型:
public class Product
{
[Key]
[JsonProperty(Order = 0)]
[JsonIgnore]
public int ProductID { get; set; }
[Required]
[JsonProperty(Order = 1)]
public string Name { get; set; }
[Required]
[JsonProperty(Order = 2)]
public virtual Shop Shop { get; set; }
[Required]
[JsonProperty(Order = 3)]
public virtual ProductCategory Category { get; set; }
[Required]
[JsonProperty(Order = 4)]
public double Price { get; set; }
[JsonProperty(Order = 5)]
public double? OldPrice { get; set; }
}
My Context has a DBSets like: 我的上下文具有一个DBSet,如:
public System.Data.Entity.DbSet<PromoCeny.Models.Product> Products { get; set; }
public System.Data.Entity.DbSet<PromoCeny.Models.ProductCategory> ProductCategories { get; set; }
public System.Data.Entity.DbSet<PromoCeny.Models.Shop> Shops { get; set; }
I was trying to access all Product
objects like: 我试图访问所有
Product
对象,例如:
db.Products
And I'm getting list of Products
but both properties Shop
and Category
are null
我正在获取
Products
列表,但属性Shop
和Category
都为null
It's strange, but I have one working solution where something like this results proper object(with all properties set properly), but I cannot find difference between these projects. 这很奇怪,但是我有一个可行的解决方案,其中类似这样的结果会生成正确的对象(所有属性均已正确设置),但是我找不到这些项目之间的区别。
I was trying to remove virtual
flag from properties in model, but this doesn't work also. 我试图从模型的属性中删除
virtual
标志,但这也不起作用。
Of course I can get list of Products like: 当然,我可以获得以下产品列表:
db.Products.Include(product => product.Shop).Include(product => product.Category)
But I would like to avoid that. 但我想避免这种情况。
Do you know how to handle that? 你知道如何处理吗?
EDIT: 编辑:
I have just figured out that i had disabled lazy loading of Entities. 我刚刚发现我已禁用实体的延迟加载。
I have removed like: 我已经删除了:
this.Configuration.LazyLoadingEnabled = false;
from Context and it's working right now. 从Context开始,现在就可以使用。
我相信您需要禁用延迟加载,只要您正确定义了关系,就应该强制链接属性加载。
The behaviour you're experiencing is caused by the lazy-load feature. 您遇到的行为是由延迟加载功能引起的。 This can be disabled in your context, like so:
可以在您的上下文中禁用它,如下所示:
public class MyContext : DbContext
{
public MyContext()
{
this.Configuration.LazyLoadingEnabled = false;
}
}
Be aware that this turns off lazy loading for everything; 请注意,这会关闭所有内容的延迟加载。 if your object graph is highly interlinked your queries may get very slow as even simple queries can end up loading a lot of data.
如果对象图是高度互连的,则查询可能会变得非常缓慢,因为即使简单的查询也可能最终加载大量数据。
Removing the virtual
modifier from a collection property should disable lazy loading for that property, but you say it doesn't... To diagnose that, we'd need more info on your EF configuration. 从collection属性中删除
virtual
修饰符应禁用该属性的延迟加载,但是您不能这样做。要诊断这一点,我们需要有关EF配置的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.