2013-02-12 11 views
5

AccountNumberが存在しないトランザクションデータを入力しようとしています。私はそれを得るために、Accountテーブルにアクセスする必要があります。私は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(); 
    } 
} 

をところであなたはこのする場所フィルタ

+1

これは完全に機能しました。優れた答え。正しい方向に私を入れてくれてありがとう。これを使って私は他にもいくつか学んだことがある。今私はViewModelが何であるか知っています。 – shaz

2

あなたの「トランザクション」型に直接キャストすることはできませんあなたのLINQクエリの「選択した新しい」セクションに突出している匿名型。

代わりに、Transactionの新しいインスタンスをプロジェクトする必要があります。次のような場合は、

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

で結合条件を複製する必要はありませんトランザクションテーブルにAccountNumberプロパティがないため、動作しません。 – shaz

+0

次回もあなたのポコクラスのプロパティをリストアップすることがありますか? :) – RainbowFish

+0

これは間違いなく良いアイデアです、私は間違いなくこの次回を覚えています。しかし、助けてくれてありがとう。 – shaz

関連する問題