如何从LINQ查询中删除重复的记录

时间:2016-08-14 17:23:01

标签: linq duplicates entity viewmodel

enter image description here

这是我的数据库的样子和我的代码,它通过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);
    }

但是当我想在View中显示它时,它会显示重复的键(例如,键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; }
}

1 个答案:

答案 0 :(得分:0)

我不知道您将如何对其进行可视化,但您有一个主Event实体,其中有2个明细WerehouseWerehouseKey个实体,它们彼此无关,因此不能像当前视图模型一样组合在一个记录中。

我看到代表此类数据的唯一方法是将视图模型更改为:

Item

并使用两个Group Join s填充它:

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