0

假设我有一个实体对象“珠宝”,它具有“姓名”和“生日”属性。我想实现一个 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);
}

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

为什么我的部分课程不返回生日石?

4

3 回答 3

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; 
        }
    }
}
于 2013-04-29T02:12:02.227 回答
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
  }
}

如果计算列用于业务逻辑,通常我在服务/业务逻辑中处理计算。所有这些都是为了确保良好的关注点分离。

注意:虽然我可能会误解您的要求

于 2013-04-29T02:22:14.600 回答
0

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

于 2013-04-29T01:46:08.520 回答