Code First select 数据 - 相关实体总是 returns null

Code First select data - Related entities always returns null

我正在尝试使用 Entity Framework 实现一个系统。这是两个类我有

Class一个

public class ConsumableGood
{
    public ConsumableGood() { }

    public Guid ConsumableGoodId { get; set; }
    public string ConsumableGoodName { get; set; }
    public string ConsumableGoodPrice { get; set; }
    public virtual Category Category { get; set; }

    public ICollection<ConsumableGoodsStock> ConsumableGoodsStocks { get; set; }

}

Class两个

public class ConsumableGoodsStock
{
    public ConsumableGoodsStock()
    {

    }

    public Guid ConsumableGoodsStockId { get; set; }
    public double ConsumableGoodPriceIn { get; set; }
    public double ConsumableGoodPriceOut { get; set; }
    public int ConsumableGoodQuantity { get; set; }
    public ConsumableGood ConsumableGood { get; set; }

    public ICollection<OrderItem> OrderItems { get; set; }
}

我正在尝试 select 来自 ConsumableGoodsStock 的记录。但问题是每次 ConsumableGood returns null 虽然它有一个值。 这是我正在尝试使用的代码。

DataTable table = new DataTable();
table.Columns.Add("Consumable Good");
table.Columns.Add("Price In");
table.Columns.Add("Price Out");
table.Columns.Add("Quantity");

var ConsumableGoodsStocks = from db in em.ConsumableGoodsStocks select db;

foreach (var consumableGoodStock in ConsumableGoodsStocks)
{
    DataRow row = table.NewRow();
    ConsumableGood consumableGood = consumableGoodStock.ConsumableGood;
    row[0] = consumableGood.ConsumableGoodName.ToString();
    row[1] = consumableGoodStock.ConsumableGoodPriceIn.ToString();
    row[2] = consumableGoodStock.ConsumableGoodPriceOut.ToString();
    row[3] = consumableGoodStock.ConsumableGoodQuantity.ToString();
    table.Rows.Add(row);
}
return table;

consumableGood 总是返回 null。提前致谢。

我认为您要查找的是延迟加载相关实体。为此,您需要将导航属性指定为 virtual。从这个 page:

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

当您在导航属性中指定 virtual 关键字时,EF 会在运行时为您的实体 类 创建动态代理。这些代理 类 负责相关实体的延迟加载行为。没有虚拟,将不支持延迟加载,并且您的导航属性将变为 null。所以你需要这样做:

public class ConsumableGoodsStock
{
    //...
    public virtual ConsumableGood ConsumableGood { get; set; }

    public virtual  ICollection<OrderItem> OrderItems { get; set; }
{

在此 link 中,您将找到支持延迟加载所需遵循的所有要求。