我的控制器中有这个代码:
public ActionResult Index()
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
using (var db = new MatchGamingEntities())
{
var MyAccount = from m in db.Accounts
join n in db.BankTransactions on m.AccountId equals n.AccountId
where m.UserId == UserId
select new BankStatement{Balance = (decimal)m.Balance, MyTransactions = m.aspnet_BankTransactions.ToList()};
return View(MyAccount.Single());
}
}
这是我的观点:
model MatchGaming.Models.BankStatement
@{
ViewBag.Title = "Index";
}
<h2>Bank Statement</h2>
<a href="/Cashier/Withdrawal">Withdrawal</a> | <a href="/Cashier/Deposit">Deposit</a><br /><br />
<fieldset>
<legend>BankStatement</legend>
<p>
Balance: @Model.Balance
</p>
</fieldset>
<table width="100%">
<tr>
<td>Created</td>
<td>Amount</td>
<td>Transaction Type</td>
</tr>
@foreach (var item in Model.MyTransactions)
{
<tr>
<td>@item.Created</td>
<td>@item.Amount</td>
<td>@item.TransactionType</td>
</tr>
}
</table>
这是我的BankStatement模型:
public class BankStatement
{
public decimal Balance {get;set;}
public List<BankTransaction> MyTransactions { get; set; }
}
我希望能够在我的两个表Accounts和BankTransactions之间进行连接查询。这是一对多关系,每个帐户可以有多个BankTransactions。我想查询并显示帐户信息,包括与之关联的所有银行对帐单。我做了一个加入以获得它,但我在处理模型时遇到了麻烦。我一直收到这个错误:
LINQ to Entities无法识别方法'System.Collections.Generic.List 1[MatchGaming.Models.BankTransaction] ToList[BankTransaction](System.Collections.Generic.IEnumerable
1 [MatchGaming.Models.BankTransaction])'方法,并且此方法无法转换为商店表达式。
答案 0 :(得分:0)
我不清楚为什么您的查询在一个地方使用db.BankTransactions
,而在另一个地方使用m.aspnet_BankTransactions
。
我怀疑你想要一个团体加入 - 像这样:
var account = from m in db.Accounts
where m.UserId == UserId
join n in db.BankTransactions
on m.AccountId equals n.AccountId
into transactions
select new BankStatement {
Balance = (decimal) m.Balance,
MyTransactions = transactions.ToList()
};
但是,如果您的模型设置了适当的关联,那么您不需要自己进行连接。只需使用:
var account = db.Accounts.Single(account => account.UserId == UserId);
return new BankStatement {
Balance = (decimal) account.Balance,
MyTransactions = account.Transactions.ToList() };
答案 1 :(得分:0)
我将假设您正在使用Entity Framework,并且您的模型中的Account和BankTransaction之间存在关系。
你可以试试这个:
public ActionResult Index()
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
using (var db = new MatchGamingEntities())
{
var myAccount = (from m in db.Account.Include("aspnet_BankTransactions")
where m.UserId = UserId
select new BankStatement{Balance = (decimal)m.Balance, MyTransactions = m.aspnet_BankTransactions).Single();
return View(myAccount);
}
}