2011-10-14 54 views
3

我非常新Linq和實體框架的工作,我有我的下面的代碼的問題。我收到錯誤無法強制類型爲'<> f__AnonymousType1`2 [System.Int64,System.String]'的對象鍵入'ConsoleApplication1.Profile'。

無法轉換類型的對象 '<> f__AnonymousType1`2 [System.Int64,System.String]' 爲類型 'ConsoleApplication1.Profile'

我的代碼是:

static void Main(string[] args) 
     { 
      ProfileEntitiesContext obj = new ProfileEntitiesContext(); 
      List<Profile> list = new List<Profile>(); 
      var test = (from c in obj.Customer 
         join a in obj.Address 
         on c.ProfileId 
         equals a.Customer.ProfileId 
         select new 
         { 
          CustomerProfileId = c.CustomerProfileId, 
          FirstName = c.FirstName 
        AddressLine1 = a.Line1 
         }).ToList().Cast<CustomerConfidentialProfile>(); 

foreach(var cust in test) // Unable to cast object of type '<>f__AnonymousType1`2 
//[System.Int64,System.String]' to type 'ConsoleApplication1.Profile'. 
      { 
       list.Add(cust); 
      } 
     } 

public class Profile 
    { 
     int _CustomerProfileId; 
     string _FirstName; 
     string _AddressLine1; 


     public int CustomerProfileId 
     { 
      get { return _CustomerProfileId; } 
      set { _CustomerProfileId = value; } 
     } 


     public string FirstName 
     { 
      get { return _FirstName; } 
      set { _FirstName = value; } 
     } 

    public string AddressLine1 
     { 
      get { return _AddressLine1; } 
      set { _AddressLine1= value; } 
     } 
} 

任何幫助將不勝感激。

回答

6

你的問題是,從LINQ查詢要返回一個匿名類型(使用new { ... }語法。

但是,你試試這個對象擠進一個List<Profile>,所以它的抱怨,你嘗試把這個匿名對象到一個列表,只需要Profile對象。

爲什麼只是不能與new Profile { ...因爲你使用的是相同的字段匿名類型,你的檔案類型做替換new { ...

並在最後刪除ToListCast

+1

你能告訴我如何將匿名對象放入上面的示例列表。 – user995099

+0

你不能使用像ArrayList這樣的弱列表。請參閱我的編輯,瞭解如何修復代碼,以便您可以像現在一樣使用強類型列表。 OMG! –

+0

OMG!你救了我半天的掙扎。問題是一個匿名對象。 –

1

您不能將匿名類型轉換爲指定類型。但是你可以直接構造一個名爲類型:

select new CustomerConfidentialProfile() 
        { 
         CustomerProfileId = c.CustomerProfileId, 
         FirstName = c.FirstName 
       AddressLine1 = a.Line1 
        }).ToList(); 
2

那是因爲匿名類型 '<> f__AnonymousType1`2 [System.Int64,System.String]' 沒有資料! (不是一個實例,也不是祖先的一個實例)。嘗試替換你的選擇是這樣的:

select new CustomerConfidentialProfile 
{ 
CustomerProfileId = c.CustomerProfileId, 
FirstName = c.FirstName, 
AddressLine1 = a.Line1, 
property assignments go futher 
}) 
+0

哈哈,永遠Google搜索,這個人告訴我需要做什麼。我在LINQ中加入了2個表格,只想從第二個表格中取出一列。圖中我應該用我想要的列創建一個類,但無法將其加載到控制器中並在視圖中進行foreach,直到我閱讀完爲止我的新課程中的專欄完全一樣。得到了我的投票。我喜歡StackOverFlow。 – JustJohn

相關問題