实体框架选择维度表中具有条件的事实表中的所有相关项

时间:2017-04-06 03:04:25

标签: c# sql-server entity-framework linq sql-server-2014

假设我有三个表,如下所示:

TShirt表

enter image description here

TShirt_Color表

enter image description here

颜色表

enter image description here

屏幕上的所需结果将是:

enter image description here

这是一个令牌输入,允许用户过滤选择颜色的T恤,当用户点击搜索时,包含颜色的T恤将显示在下面的网格中。

我正在使用Entity框架进行搜索,用户选择颜色后,系统将使用下面的Linq进行搜索(userSelectedColor是用户选择颜色的List):

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 Server 2014

1 个答案:

答案 0 :(得分: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)
              }

这样,您可以使用所有颜色创建组,并完全删除不包含所选颜色的组而不更改其他组,而不是在组中不包括这些颜色。

相关问题