我是Entity Framework的新手,有人可以告诉我们如何从以下查询中提取数据并将结果传递给视图。
public ActionResult Index()
{
var query = (from c in db.Customers
join b in db.Banks on c.Id equals b.CustomerId
join bt in db.BankTransactions on b.Id equals bt.BankId
where c.Id == 1
orderby bt.Id descending
select new
{
Name = c.Name,
Balance = bt.Balance
}).Take(1);
//I want to pass Customer Name and Customer Balance to the view
return View();
}
答案 0 :(得分:2)
创建视图模型
public class CustomerVM
{
public string Name { get; set; }
public decimal Balance { get; set; }
}
并将您的查询修改为
var query = (from c in db.Customers ...
....
select new CustomerVM
{
Name = c.Name,
Balance = bt.Balance
}).FirstOrDefault();
然后
return View(query);
查看
@model YourAssembly.CustomerVM
...
@Html.DisplayFor(m => m.Name)
...
答案 1 :(得分:1)
我没有编译这个snipet来检查,但为了解决你的问题,你可以这样做:
NewObject balanceInfo = query.AsEnumerable().Select(p => new NewObject
{
CostumerName = p.Name,
CostumerBalance = p.Balance
});
当我的方法返回列表时,我做了很多。正如我所说,我没有进行查询并编译进行测试,但我相信这可以解决您的问题。