【发布时间】:2013-04-29 01:36:10
【问题描述】:
假设我有一个实体对象“珠宝”,它具有“姓名”和“生日”属性。 我想实现一个 LINQ 查询,它返回一个具有“姓名”、“生日”和“生日石”的对象。所以我像这样扩展“珠宝”:
public partial class JewelStones : Jewels
string Birthstone = null;
public void JewelsWithStone()
{
this.Birthstone = "diamond";
//(we figure out what stone applies to the month here)
}
我可以做到这一点,我认为我在正确的轨道上,但我不知道如何编写 LINQ 查询并取回包含生日石的对象,因此我可以将该对象绑定到网格这将显示生日石,我没有将其存储在任何地方,因为它总是经过计算(这是假数据,如果不合逻辑,请见谅)。
List<Jewel> jewels = new List<Jewel>;
using (jewelentities db = new jewelentities())
{
jewels = (from j in db.Jewels select j).ToList();
}
如何用姓名、生日和生日石填充我的 JewelStone 对象?
如果我在这里没有遵循最佳做法,请告诉我!
编辑
我尝试向实体分部类添加分部类。当我现在引用 Jewel 类时,它“看到”Birthstone 属性,但它为空。我不知道为什么?这是部分类:
public partial class Jewel
{
private string _birthstone;
public string Birthstone
{
get { return _birthstone; }
set
{
JewelBusiness jewelBusiness = new JewelBusiness();
_birthstone = jewelBusiness.RequestBirthstone(birthmonth);
}
}
}
如果我使用 LINQ 查询实体以获取 Jewel 记录列表,我会从实体中获取所有信息,Jewel.Birthstone 在那里,但它为空。但是,如果我对结果进行 foreach ---
foreach (Jewel j in jewels)
{
string stone = jewelBusiness.RequestBirthstone(j.Birthmonth);
}
stone 将等于预期结果(该月的生日石)。
为什么我的部分班级不归还生日石??
【问题讨论】:
-
查看我的更新答案
-
我认为改变属性的get方法并检查该字段是否为空,是要走的路。但请记住,您不能在 entityframe-work 查询中对实体使用扩展属性,因此您必须先使用 toList,然后再查询扩展属性。
标签: c# linq entity-framework asp.net-4.5