2014-02-07 55 views
0

我想自己把下面的代碼放在一個類,這樣我可以重複使用它:查詢使用一類具有LinqToSql

 var activePersons = (from p in _dataContextOrders.Persons 
          select new 
          { 
           p.ID, 
           p.WindowsUserID, 
           p.Name, 
           p.CommonShortName, 
           p.TeamID, 
           p.Telephone, 
           p.Fax, 
           p.Email, 
           p.FMSBudgetOfficerID, 
           p.Active 
          }).Where(p => p.Active).OrderBy(p => p.CommonShortName); 

所以我可以返回對象activePersons。我將這個替換這一切:

var activePersons = DataAccessLayer.ActivePersons.GetActivePersons(); 

但進一步下跌的一頁,我有這樣的:

var currentUser = activePersons.SingleOrDefault(p => p.WindowsUserID == strWindowsSessionUserId); 

這現在返回編譯錯誤。有沒有辦法解決這個問題?

+1

你得到了什麼錯誤? – Tigran

+1

您接受了[您先前的問題]的錯誤答案(http://stackoverflow.com/q/21630745/1159478)。如果你對這個問題使用了適當的答案,你就不會在這種情況下。 – Servy

回答

1

您收到錯誤的原因是因爲您在查詢中使用new關鍵字選擇的匿名對象。你不能從你的方法返回匿名對象,所以我想你是返回object。現在對於你的方法調用者來說,它是一個object類型對象,它並不公開查詢中選擇的所有屬性,(因爲不知道類型,所以不能將它轉換爲類型)因此,錯誤。

需要創建一個新的類和所有的屬性,並返回IEnumerable<yourClass>從該方法。

有一個way to return anonymous object mentioned by Jon Skeet但他不推薦它。

像定義一個類:

class ReturnedObject 
{ 
    public int ID { get; set; } 
    public string WindowsUserID { get; set; } 
    //..... rest of the properties 
} 

,然後在您的查詢:

var activePersons = (from p in _dataContextOrders.Persons 
     select new ReturnedObject 
     { 
      ID = p.ID, 
      WindowsUserID = p.WindowsUserID, 
      //rest of the properties 

在你的方法指定的返回類型:

public IEnumerable<ReturnedObject> GetActivePersons(//parameters 
+0

謝謝你的幫助。我最終得到了這個工作。 DRY編程! –

+0

@SteveStaple,歡迎您的光臨,但您在之前的問題中接受了[錯誤答案](http://stackoverflow.com/a/21631133/961113)以獲得類似主題。 – Habib