2013-04-29 70 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