How to extract data from Linq query

asp.net asp.net-mvc-4 c# entity-framework-6 linq

Question

I am new to Entity Framework, can anybody please tell how to extract data from following query and pass the result to the view.

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();
    }
1
0
11/12/2014 11:28:20 AM

Popular Answer

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)
...
2
12/10/2014 1:35:00 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow