linq中的外部联接并根据第二个表中的条件获取记录

时间:2018-05-03 08:16:34

标签: c# linq join

Tables : 
Component        ComponentRights
--------------        ----------------  
ComponentId (PK)      ComponentRightsID
ComponentName         ComponentId (FK)
                      RoleId 

让我们说MyRoleId = 2;

现在,我希望从两个表中获取所有记录,但是基于一个条件。如果我得到相同的记录但具有不同的RoleId,那么它应该只占用RoleId = MyRoleId的一条记录。如果没有重复项,则跳过条件。

Example:
Record 1:
------------
ComponentId = 1,
ComponentName = 'SampleComponent'
RoleId = 1

Record 2 :
-----------
ComponentId = 1,
ComponentName = 'SampleComponent'
RoleId = 2

* So In this case I should get Record 2.

Here is my sample code:



var Components = (from components in MyDB.Component
                                  join componentRights in MyDB.ComponentRights on components.ComponentId equals componentRights.ComponentId
                                  into AllComponents
                                  from allComponent in AllComponents.DefaultIfEmpty()

                                  where !(components.IsDeleted)

                                  select new ComponentRightsModel()
                                  {

                                      ComponentRightsId = (!allComponent.IsDeleted) ? (Guid?)allComponent.ComponentRightsId : null,
                                      ComponentId = components.ComponentUID,
                                      ComponentName = components.ComponentName,
                                      RoleId = allComponent.RoleId
                                  }).ToList();

1 个答案:

答案 0 :(得分:0)

我建议将问题分解为单独的陈述......

var Components = (from components in MyDB.Component
                  join componentRights in MyDB.ComponentRights on components.ComponentId equals componentRights.ComponentId
                                  into AllComponents
                                  from allComponent in AllComponents.DefaultIfEmpty()

                              where !(components.IsDeleted)
                              select new ComponentRightsModel()
                              {
                                  ComponentRightsId = (!allComponent.IsDeleted) ? (Guid?)allComponent.ComponentRightsId : null,
                                  ComponentId = components.ComponentUID,
                                  ComponentName = components.ComponentName,
                                  RoleId = allComponent.RoleId
                              });
var uniqueComponetIds = Components.GroupBy(x=>x.ComponentId).Select(x=> new {ComponentId = x.Key, Count = x.Count(y=>y.RoleId)}).Where(x=>x.Count == 1).Select(x=>x.ComponentId);

var filteredDuplicates = Components.Where(x=> !uniqueComponetIds.Contains(x.ComponentId) && x.RoleId == MyRoleId);

var finalComponents = Components.Where(x=> uniqueComponetIds.Contains(x.ComponentId).Concat(filteredDuplicates);

请注意,此查询还会过滤掉组件重复的记录,但收集的重复文件没有碰巧具有RoleId == MyRoleId的角色。如果您想要包含这些内容,也可以添加第三个语句来捕获这些内容。