[英]Cannot return proper model into view when doing a join linq query
我的控制器中有以下代碼:
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])'方法,以及此方法方法不能轉換為商店表達式。
為什么你的查詢使用這不是很清楚,我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() };
我將假設您使用的是實體框架,並且模型中的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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.