2017-04-06 19 views
0

假设我有一个像下面三个表:实体框架选择维度表实际上是表中的所有相关物品与条件

T恤表

enter image description here

TShirt_Color表

enter image description here

颜色表

enter image description here

并在屏幕上所需的结果将是:

enter image description here

这是一个令牌输入让用户与颜色选择,并且当用户点击搜索,所述T过滤的T恤包含颜色的衬衫将显示在下面的网格中。

我使用实体框架的搜索和用户选择后的颜色,该系统将搜索用下面的LINQ(userSelectedColor是用户所选择的颜色的列表):

var results = from a in TShirt 
       join b in TShirt_Color on a.Id equals b.TShirtId into c 
       from d in c.DefaultIfEmpty() 
       join e in Color on c.ColorId equals e.Id into f 
       from g in f.DefaultIfEmpty() 
       where userSelectedColor.Contains(g.Id) 
       group new {a, g} by 
       new 
       { 
        a.Id, 
        a.Name 
       } into h 
       select new 
       { 
        ID = a.Id, 
        TShirtname = a.Name, 
        AvailableColors = h.Select(i=>i.g.ColorName) 
       } 

但上面的查询有一个问题:

如果用户选择 “黄色”,结果将是:

enter image description here

它滤除了其他颜色。

如何解决这个问题?

供您参考,我使用EF6和SQL服务器2014

回答

2

你应该过滤你的群体,而不是颜色:

var results = from a in TShirt 
       join b in TShirt_Color on a.Id equals b.TShirtId into c 
       from d in c.DefaultIfEmpty() 
       join e in Color on c.ColorId equals e.Id into f 
       from g in f.DefaultIfEmpty() 
       group new {a, g} by 
       new 
       { 
        a.Id, 
        a.Name 
       } into h 
       where userSelectedColor.Intersect(h.Select(z=>z.g.Id)).Any() 
       select new 
       { 
        ID = a.Id, 
        TShirtname = a.Name, 
        AvailableColors = h.Select(i=>i.g.ColorName) 
       } 

这种方式,您可以创建组,所有的颜色和在不更改其他组的情况下完全删除不包含所选颜色的组,而不是在组中包含这些颜色。

+1

嗨我修改了你的答案一点,因为我没有按“g”分组,“g”和“h”有一对多的关系,所以它是一个列表。你的解决方案正在工作 – User2012384