【问题标题】:Code First select data - Related entities always returns null代码优先选择数据 - 相关实体始终返回 null
【发布时间】:2015-03-16 15:02:28
【问题描述】:

我正在尝试使用实体框架来实现一个系统。这是我的两个课程

一级

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; }

}

二班

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; }
}

我正在尝试从 ConsumableGoodsStock 中选择记录。但问题是每次 ConsumableGood 返回 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。提前致谢。

【问题讨论】:

  • 可以把你的 DbContext 放在这里。

标签: c# entity-framework ef-code-first code-first


【解决方案1】:

我认为您正在寻找的是延迟加载相关实体。为此,您需要将导航属性指定为virtual。来自这个page

延迟加载是一个实体或集合 实体第一次从数据库中自动加载 访问引用实体/实体的属性。使用时 POCO实体类型,懒加载是通过创建实例来实现的 派生代理类型,然后覆盖 virtual 属性以添加 装载钩。

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

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

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

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

【讨论】:

  • 很高兴知道 ;),如果您认为我的回答解决了您的问题,请单击复选标记考虑 accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
猜你喜欢
  • 1970-01-01
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 2014-04-04
  • 2014-05-09
  • 1970-01-01
  • 2014-12-09
相关资源
最近更新 更多