6

AccountNumberが存在しないトランザクションデータを入力しようとしています。それを取得するには、Accountテーブルにアクセスする必要があります。IEnumerableを返そうとすると、次のエラーが発生します

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;

    }
4

2 に答える 2

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();
    }
}

ところで、どこのフィルターで重複した結合条件は必要ありません

于 2013-02-12T16:56:23.837 に答える
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();
于 2013-02-12T16:46:56.487 に答える