2013-04-29 71 views
0

假设我有一个实体对象'Jewels',它具有属性'Name'和'Birthdate'。 我想实现一个LINQ查询,它返回一个具有'Name','Birthdate'和'Birthstone'的对象。所以,我向“珠宝”这样的:将实体对象扩展为包含计算属性

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查询并取回对象包括Birthstone,因此我可以将该对象绑定到一个表示Birthstone的网格,我不会将它存储在任何地方,因为它始终是计算的(这是假装数据,如果不合逻辑)。

List<Jewel> jewels = new List<Jewel>; 
using (jewelentities db = new jewelentities()) 
{ 
    jewels = (from j in db.Jewels select j).ToList(); 
} 

如何用名称,出生日期和幸运石填充我的宝石对象?

如果我在这里没有遵循最佳实践,请告诉我!

编辑

我已经尝试添加一个部分类的实体部分类。当我现在参考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.Birthstone是存在的,但它是空的。然而,如果我对结果进行foreach ---

foreach (Jewel j in jewels) 
{ 
    string stone = jewelBusiness.RequestBirthstone(j.Birthmonth); 
} 

石头将等于预期的结果(该月的诞生石)。

为什么我的部分课程没有回归诞生?

+0

看看我的更新答案 – 2013-04-29 08:46:08

+0

我想改变的属性get方法,并检查该字段为空,是要走的路。但是请记住,您不能在entityframe-work查询中将扩展属性用于实体,因此您必须先使用toList,然后查询扩展属性。 – 2013-04-29 08:57:46

回答

1

我不确定我是否正确理解您的要求。但是,如果你不想存储Birthstone,但计算它的飞行,只是改变你的代码

public partial class Jewel 
{ 
    private string _birthstone; 
    public string Birthstone 
    { 
     get 
     { 
      if (_birthstone == null) 
      { 
        JewelBusiness jewelBusiness = new JewelBusiness(); 
        _birthstone = jewelBusiness.RequestBirthstone(birthmonth); 
      } 
      return _birthstone; 
     } 
    } 
} 
0

在部分类中是不是您的Jewels EntityObject?你很可能只是添加一个Jewels部分类来“扩展”它并在那里添加想要的属性。

+0

这就是我正在尝试做的事,我不知道如何实现它,或者如果这是在绑定之前向实体对象添加属性的最佳方式。 – Jazzy 2013-04-29 03:43:37

0

对于我来说,这取决于其中用于计算列中的逻辑所在。

如果它驻留在数据库中,那么您必须在Linq中进行连接查询。我假设在这种情况下,您有一个名为BirthStoneTable的表格,其中月份为关系。我不建议在linq查询中添加三元操作,例如select j.BirthDate.Month == 1 ? "Diamond" : //etc etc。很难调试和跟踪(另外还有代码覆盖的原因)。

如果它驻留在UI特定(仅提高显示),我通常添加类型铸类,如:

public class JewelUI{ 
    public explicit operator JewelUI(Jewel jewel){ 
    JewelUI jewelUI = new JewelUI(); 
    // assign birthdate and name 
    jewelUI.BirthStone = GetBirthStone(jewel.BirthDate.Month); 
    } 

    public string BirthStone{get;set;}; 

    public string GetBirthStone(int month){ 
    if(month == 1) return "Diamond"; 
    //etc etc 
    } 
} 

如果计算出的列的业务逻辑中使用,一般我处理服务/业务逻辑中的计算。所有这一切都是为了确保良好的分离关注。

注:我可能误解了你的要求,虽然

+0

我想你确实明白了,你的榜样是有道理的。简而言之,我需要一个具有数据库属性的对象,然后是一些。 – Jazzy 2013-04-29 03:47:32