EF4.1-属性在运行时评估为null
本文关键字:评估 null 运行时 属性 EF4 | 更新日期: 2023-09-27 18:10:43
我首先使用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查询创建一个CallItems集合时,我无法访问每个CallItems附带的产品的属性,例如
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;
因为愈伤组织。产品正在评估为null。这与延迟加载有关吗?如果是,我该如何解决问题?
RunSheet是另一个类,nrs是一个实例,我想用CallItem的Product代码填充其属性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;
}
public class CallItem
{
public int Id { get; set; }
public float Discount { get; set; }
public virtual Product Product { get; set; }
}
public 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; }
}
using (var context = new StackOverFlowContext())
{
var p = new Product
{
Id = 1,
BaseCost = 200,
Code = "Hola",
Description = "Soe description",
Ingredients = "Some ingredients",
IsWasteOil = true,
Name = "My Product",
UnitSize = 10
};
var item = new CallItem
{
Id = 101,
Discount = 10,
Product = p
};
context.CallItems.Add(item);
context.SaveChanges();
var result = from temp in context.CallItems
select temp;
Console.WriteLine("CallItem Id"+result.First().Id);
Console.WriteLine("ProductId"+result.First().Product.Id);
}
我写了上面的代码和下面的输出
CallItemId 1
ProductId 1
sql Profiler显示了这个
SELECT TOP (1)
[c].[Id] AS [Id],
[c].[Discount] AS [Discount],
[c].[Product_Id] AS [Product_Id]
FROM [dbo].[CallItems] AS [c]
太长了,无法发表评论,所以我把它放在这里。