2013-02-12 143 views
5

我想填充AccountNumber不存在的Transaction數據。我需要訪問帳戶表來獲取。我收到以下錯誤在那裏我試圖返回的IEnumerable無法將類型'System.Collections.Generic.IEnumerable <AnonymousType#1>'隱式轉換爲'System.Collections.Generic.List <modelClass>

不能隱式類型轉換System.Collections.Generic.IEnumerable<AnonymousType#1>System.Collections.Generic.List<ProjectModel.Transaction>

錯誤顯示在.ToList()的頂部;部分代碼。我究竟做錯了什麼?

代碼:

public static IEnumerable<Transaction>GetAllTransactions() 
    { 
     List<Transaction> allTransactions = new List<Transaction>(); 
     using (var context = new CostReportEntities()) 
     { 
      allTransactions = (from t in context.Transactions 
           join acc in context.Accounts on t.AccountID equals acc.AccountID 
           where t.AccountID == acc.AccountID 
           select new 
           { 
            acc.AccountNumber, 
            t.LocalAmount 
           }).ToList(); 

     } 
     return allTransactions; 

    } 

回答

5

匿名類型列表不能被轉換爲事務列表。看起來像你的Transaction類沒有AccountNumber屬性。你也不能從方法中返回匿名對象。所以,你應該創建一些類型將舉行所需數據:

public class AccountTransaction 
{ 
    public int LocalAmount { get; set; } 
    public int AccountNumber { get; set; } 
} 

,並返回這些對象:

public static IEnumerable<AccountTransaction> GetAllTransactions() 
{  
    using (var context = new CostReportEntities()) 
    { 
     return (from t in context.Transactions 
       join acc in context.Accounts 
        on t.AccountID equals acc.AccountID    
       select new AccountTransaction { 
        AccountNumber = acc.AccountNumber, 
        LocalAmount = t.LocalAmount 
       }).ToList(); 
    } 
} 

BTW你不需要重複在過濾器

+1

這工作完美。優秀的答案。非常感謝讓我走向正確的方向。做到這一點,我也學到了其他一些東西。現在我知道什麼是ViewModel。 – shaz 2013-02-12 21:33:52

2

你正在你的LINQ查詢的「選擇新的」一節中突出不能直接鑄造到你的「交易」類型的匿名類型。

相反,您應該投影一個新的事務實例。以下可能有所幫助:

allTransactions = (from t in context.Transactions 
    join acc in context.Accounts on t.AccountID equals acc.AccountID 
    where t.AccountID == acc.AccountID 
    select new Transaction() 
    { 
     AccountNumber = acc.AccountNumber, 
     LocalAmount = t.LocalAmount 
    }).ToList(); 
+0

連接條件,這將不起作用,因爲我在Transaction表中沒有AccountNumber屬性。 – shaz 2013-02-12 21:34:53

+0

下次也許會列出您的poco課程的屬性? :) – RainbowFish 2013-02-13 08:32:10

+0

這絕對是一個好主意,我一定會記得下次。感謝您的幫助。 – shaz 2013-02-13 08:57:36

相關問題