【发布时间】:2019-05-15 14:28:15
【问题描述】:
我有三个简单的实体 - Basket、Product 和 BasketItem。 因此,通过 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