Innov Bee Innov Bee -4 years ago 147
C# Question

Passing ef query to view

This works:

var model =
(from t in _db.Tickets
from p in _db.Cust
where t.Id == 5 && t.Id == p.cust_id
orderby t.Id descending
select new tks_custs
{
Tks = t,
Custs = p
});


But i want to achieve like this to use group by:

var model = _db.Tickets
.Join(_db.Cust,
t => t.Id,
w => w.cust_id,
(t, w) => new { Tks = t, Custs = w })
.Where(t => t.Tks.Id == 5).OrderByDescending(w => w.Tks.Id)
.GroupBy(t => t.Tks.Name).ToList();


My view declaration is currently:

@model IQueryable<test.ViewModels.tks_custs>

Answer Source

You should create your VieModel object (tks_custs) same way like you do it your first query. Now you try to pass DB model (actually not BD model, but anonymouse IGrouping object).

It should be something like this:

var model = _db.Tickets
            .Join(_db.Cust,
                t => t.Id,
                w => w.cust_id,
                (t, w) => new { Tks = t, Custs = w })
            .Where(t => t.Tks.Id == 5).OrderByDescending(w => w.Tks.Id)
            .GroupBy(t => t.Tks.Name).ToList()
            .Select(x => new tks_custs //here you creating your ViewModel
            {
                Tks = x.FirstOrDefailt().Tks,
                Custs = x.FirstOrDefailt().Custs 
            });

You may notice FirstOrDefailt(). You need it becouse after GroupBy you may have many entities in group.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download