2017-03-01 99 views
0

這工作:傳遞EF查詢,查看

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 
    }); 

但我想實現這樣通過使用組:

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(); 

我認爲聲明是目前:

@model IQueryable<test.ViewModels.tks_custs> 
+0

錯誤是。視圖接受iqueryable,但數據庫查詢通過 –

+0

Pass ViewModel not Model .... – yash

回答

1

您應該像創建第一個查詢一樣創建VieModel對象(tks_custs)。現在您嘗試傳遞數據庫模型(實際上不是BD模型,但是匿名對象爲IGrouping對象)。

應該是這樣的:

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 
      }); 

您可能會注意到FirstOrDefailt()。你需要它,因爲在GroupBy之後,你可能有許多組中的實體。