I am trying to populate Transaction data where AccountNumber does not exist. I need to access the Account table to get that. I am getting the following error where I am trying to return IEnumerable
Cannot implicitly convert type System.Collections.Generic.IEnumerable<AnonymousType#1>
to System.Collections.Generic.List<ProjectModel.Transaction>
The error is shown on top of .ToList(); part of the code. What am I doing wrong?
the code is:
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;
}
List of anonymous types cannot be casted to list of transactions. Looks like your Transaction
class do not have AccountNumber
property. Also you cannot return anonymous objects from methods. So you should create some type which will hold required data:
public class AccountTransaction
{
public int LocalAmount { get; set; }
public int AccountNumber { get; set; }
}
And return these objects:
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 you don't need duplicate join condition in where filter
The anonymous type which you're projecting in the "select new" section of your Linq query cannot be casted directly to your "Transaction" type.
Instead, you should project a new instance of Transaction. The following might help:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With