2016-08-14 93 views
1

enter image description here如何從LINQ查詢刪除重複記錄

這是我的數據庫看起來像我的條碼是由WhID

public ActionResult Details(int? id) 
    { 
     if (id == null) 
     { 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 
     var viewModel = 
      (from Wh in db.Werehouses 
      join WhK in db.WerehouseKeys on Wh.WhID equals WhK.WhID 
      join Itm in db.Items on Wh.WhID equals Itm.WhID 
      where Wh.WhID == id 
      select new WerehouseViewModel { Werehouse = Wh, WerehouseKey = WhK, Item = Itm }); 
     if (viewModel == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(viewModel); 
    } 

會從數據庫中的所有數據,但是,當我想表明它在查看它顯示重複的鍵(例如鍵1,鍵2,鍵3,鍵1,鍵2,鍵3等)和項目(項目1,項目2,項目1,項目2等)。我如何刪除查詢中的重複項?

這是我的ViewModel

public class WerehouseViewModel 
{ 
    public Werehouse Werehouse { get; set; } 
    public WerehouseKey WerehouseKey { get; set; } 
    public Item Item { get; set; } 
} 
+0

嘛,要加入'Werehouses' (1)到2個不同的(很多)實體,所以結果是相關的'WerehouseKeys'和'Items'記錄的笛卡爾積。您可能需要考慮更改視圖模型並使用組聯接。 –

+0

非常感謝您的建議,請問您如何編輯它? – Cezar

+0

我會讓'WerehouseViewModel'成爲這樣的'Public Werehouse Werehouse {get;組; } public List WerehouseKeys {get;組; } public List Items {get;組; }' –

回答

0

我不知道你打算如何可視化它,但你有一個主Werehouse實體2詳細WerehouseKeyItem實體,它們是彼此無關,因此不能像您當前的視圖模型那樣合併到單個記錄中。

我看到代表這些數據的唯一方法是向視圖模型更改爲:

public class WerehouseViewModel 
{ 
    public Werehouse Werehouse { get; set; } 
    public List<WerehouseKey> WerehouseKeys { get; set; } 
    public List<Item> Items { get; set; } 
} 

,它使用兩個Group Join小號填充:

var viewModel = 
    (from Wh in db.Werehouses 
    join WhK in db.WerehouseKeys on Wh.WhID equals WhK.WhID into keys 
    join Itm in db.Items on Wh.WhID equals Itm.WhID into items 
    where Wh.WhID == id 
    select new WerehouseViewModel 
    { 
     Werehouse = Wh, 
     WerehouseKeys = keys.ToList(), 
     Items = items.ToList() 
    }) 
    .FirstOrDefault(); 
+0

這就是我的問題的答案。非常感謝! – Cezar