繁体   English   中英

延迟加载EF MVC的问题

[英]Problems with lazy loading EF MVC

我对EF中的一些相关实体有疑问。

这是我的产品类别:

public class Product
{
    public int Id { get; set; }
    public int AtpID { get; set; }
    public int SupplierID { get; set; }
    public string AtpName { get; set; }
    public string Name { get; set; }
    public string ArticleNo { get; set; }
    public string SupplierNo { get; set; }
    public string AtpPrice { get; set; }
    public string AtpStock { get; set; }
    public string AtpDeliveryDays { get; set; }
    public bool FitsAllCars { get; set; }
    public int? CategoryId { get; set; }

    public virtual ICollection<ProductReference> ProductReferences { get; set; }
    public virtual ICollection<ProductDetail> ProductDetails { get; set; }
}

这是ProductDetails类:

public class ProductDetail
{
    public int Id { get; set; }

    [ForeignKey("ProductId")]
    public virtual Product Product { get; set; }
    public int ProductId { get; set; }

    public int ProductDetailTypeId { get; set; } 
    public int ProductDetailKeyId { get; set; }       
    public string AtpTextKey { get; set; }
    public string AtpTextValue { get; set; }
    public string TextKey { get; set; }
    public string TextValue { get; set; }
    public bool IsVisible { get; set; }
    public bool Checked { get; set; }

}

问题是,未在产品中加载ProductDetails,如您在所附的屏幕截图中所见,它给了我一个错误:

在此处输入图片说明

ProductReferences已正确加载,只有ProductDetails才出现此问题。 您能帮我解决这个问题吗? 我不知道什么会导致这个问题。 谢谢!

选择时,请使用包括:

 _context.Product.Include('ProductDetails').ToList()

如果要启用延迟加载,则请检查是否在DBContext类中设置了该属性,如果为false,则不会加载。 那么您需要使用我的答案中提到的“急切加载”

  this.Configuration.LazyLoadingEnabled = true; 

在ProductDetails中添加以下内容:

var products = await _ctx.Products
                .Include(p => p.ProductDetails)
                .ToListAsync();

我猜您遇到了循环引用引起的异常。 请注意,产品包含对ProductDetails的引用,而ProductDetails则包含对Product的引用。 当您尝试序列化此聚合(对象图)循环引用时,将引发异常。

最好的方法是使用DTO仅传输要在特定视图中使用的数据。 DTO应该仅具有简单的属性,因此不会产生循环引用错误。

暂无
暂无

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

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