gpt4 book ai didi

c# - EF4.1 - 属性在运行时评估为 null

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:13 25 4
gpt4 key购买 nike

我首先使用 EF4.1 代码创建一个带有 SQL CE 4 后端的简单数据库应用程序。我有一个 Product 类和一个 CallItem 类定义如下:

    class CallItem
{
public int id { get; set; }
public float discount { get; set; }
public virtual Product Product { get; set; }
}

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

public decimal BaseCost { get; set; }
public int UnitSize { get; set; }
public bool isWasteOil { get; set; }

public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Ingredients { get; set; }
}

编辑 - 当我使用 LINQ 查询创建 CallItem 的集合时,我无法访问附加到每个 CallItem 的产品的属性,例如

var callItems = from ci in context.CallItems select ci;

foreach(CallItem callItem in callItems)
{
RunSheet nrs = new RunSheet();
nrs.prodCode = callitem.Product.Code;
}

查询数据库显示正在填充 CallItems 中的 Productid。但是,以下行会在运行时生成 NullReferenceException:

nrs.prodCode = callitem.Product.Code;

因为 callitem.Product 评估为 null。这与延迟加载有关吗?如果是,我该如何解决该问题?

RunSheet 是另一个类,nrs 是一个实例,我想用 CallItem 的产品代码填充其属性“prodCode”。

谢谢!

最佳答案

根据您所展示的代码,它应该可以工作。您是否尝试过显式加载?

var callItems = from ci in context.CallItems.Include(c => c.Product) select ci;

foreach(CallItem callItem in callItems)
{
RunSheet nrs = new RunSheet();
nrs.prodCode = callitem.Product.Code;
}

关于c# - EF4.1 - 属性在运行时评估为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7703842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com