【问题标题】:Entity Framework Core not loading 1 to 0 foreign key entityEntity Framework Core 未加载 1 到 0 外键实体
【发布时间】:2019-05-15 14:28:15
【问题描述】:

我有三个简单的实体 - BasketProductBasketItem。 因此,通过 BasketItem 将 Product 添加到 Basket。每个 BasketItem必须连接到一个 Product 和一个 Basket,但 Product 不必连接到 BasketItem(即尚未添加到任何购物篮)。

Basket 和 BasketItem 具有 1 对多的关系,而 BasketItem 和 Product 具有 1-0 的关系,这意味着 Product 可以在 Basket 中(通过 BasketItem),但不是必须的。

我已经以常规方式设置了一个 DbContext,除了 Product 实体在通过 BasketItem 访问时为空之外,一切正常,即实体框架根本不加载它。例如

basket.BasketItems.FirstOrDefault().Product 给出 null。

我已经在谷歌上搜索了几个小时,但找不到解决方案。我还尝试了以下几种变体:

builder.Entity<BasketItem>().HasOne(p => p.Product);

但没有一个有效。 代码如下:

public class Basket
{
    [Key]
    public int ID { get; set; }

    public ICollection<BasketItem> BasketItems { get; set; } = new List<BasketItem>();
}

}

public class BasketItem
{
    public int ID { get; set; }

    public int ProductID { get; set; }

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

    public int BasketID { get; set; }

    [ForeignKey("BasketID")]
    public virtual Basket Basket { get; set; }

    public int ProductQuantity { get; set; }

}

public class Product
{
    public int ID { get; set; }

    [Required]
    public string ProductName { get; set; }

    public string Description { get; set; }

    public double Price { get; set; }
}

在我的上下文设置中:

     builder.Entity<Product>().HasData(new Product() { ID = 1, ProductName = "Harry Potter hardback collection", Description = "All 7 Harry Potter books in hardback.", Price = 150.00 });

...

builder.Entity<Basket>().HasData(new Basket() { ID = 1, BasketTotalPrice = 750 });

builder.Entity<BasketItem>().HasOne(p => p.Product);

builder.Entity<BasketItem>().HasData(new BasketItem() { ID = 1, BasketID = 1, ProductID = 1, ProductQuantity = 2 });

【问题讨论】:

  • 你试过 context.Basket.Include(b => b.BasketItems).ThenInclude(bi => bi.Product).FirstOrDefault().Product 吗?
  • @darem 这是一个,我错过的是 ThenInclude。队友的欢呼声。留下回复,以便我将其标记为答案

标签: asp.net-core foreign-keys entity-framework-core lazy-loading


【解决方案1】:

Loading Related Data 文档的部分。

您必须使用Include() 方法

【讨论】:

  • 实际上我错过了 Darem 提到的 ThenInclude(),但我也在你的链接上找到了它,谢谢
【解决方案2】:

正如评论中提到的,你必须首先Include() BasketItmens。 ThenInclude() 产品。

所以在你的情况下,解决方案是

context.Basket.Include(b => b.BasketItems).ThenInclude(bi => bi.Product).FirstOrDefault().Product

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2020-06-03
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2022-09-22
    相关资源
    最近更新 更多