我首先使用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; }
}
edit - 当我使用LINQ查询创建CallItems集合时,我无法访问附加到每个CallItem的Product的属性,例如
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是一个实例,其属性'prodCode'我想用CallItem的Product代码填充。
谢谢!
答案 0 :(得分:2)
从那段代码中你所展示的它应该可行。你尝试过显式加载吗?
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;
}
答案 1 :(得分:0)
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]
评论太长了,所以我把它放在这里。