[英]How to extract data from Linq query
I am new to Entity Framework, can anybody please tell how to extract data from following query and pass the result to the view. 我是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();
}
Create a view model 创建一个视图模型
public class CustomerVM
{
public string Name { get; set; }
public decimal Balance { get; set; }
}
and modify your query to 并将您的查询修改为
var query = (from c in db.Customers ...
....
select new CustomerVM
{
Name = c.Name,
Balance = bt.Balance
}).FirstOrDefault();
then 然后
return View(query);
View 视图
@model YourAssembly.CustomerVM
...
@Html.DisplayFor(m => m.Name)
...
I didn't compile this snipet to check, but to solve your problem you could do something like this: 我没有编译此摘要来进行检查,但是要解决您的问题,您可以执行以下操作:
NewObject balanceInfo = query.AsEnumerable().Select(p => new NewObject
{
CostumerName = p.Name,
CostumerBalance = p.Balance
});
I do it a lot when my methods return lists. 当我的方法返回列表时,我会做很多事情。 As I told, I didn't make a query and compiled to test, but I believe that this should solve your problem.
正如我所说的,我没有进行查询并进行编译以进行测试,但是我相信这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.