Linq union所有相当于sql代码

时间:2014-03-25 06:26:20

标签: sql linq union-all

我有以下疑问:

var majorClients = maj in dbContext.MajorClients
                   where (maj.startdate > startDate)
                   where (maj.status == "Active")
                   Select new Client{EntityPK = maj.mjPrimaryKey,Name = maj.name, Type = "Maj"};

var minorClients = min in dbContext.MinorClients
                   where (min.startdate > startDate)
                   where (min.status == "Active" || min.status== "Inactive")
                   Select new Client{EntityPK = min.mnPrimaryKey,Name = min.name, Type = "Min"};

有些客户端可以出现在主表和次表中。我想返回两个表中所有客户端的列表,但是如果按名称匹配客户端,那么我只想从majorClients表中返回匹配的记录。

我编写了一个sql查询来返回结果:

SELECT mjPrimaryKey AS EntityPK,name,'Maj' AS TYPE 
FROM majorClients 
WHERE status = 'Active' AND startDate > @startDate
UNION ALL
SELECT mnPrimaryKey,name,'Min' FROM minorClients
WHERE status IN ('Active','Inactive') AND startDate > @startDate
WHERE name NOT IN (SELECT name FROM majorClients WHERE status = 'Active' AND startDate > @startDate)

我如何在linq中表示此查询?

1 个答案:

答案 0 :(得分:2)

试试这个linq。要从minorClients中排除重复项,我使用了Contains方法。联合所有对象 - Union方法:

var majorClients = from maj in dbContext.MajorClients
                   where maj.startdate > startDate
                        && maj.status == "Active"
                   select new Client
                    {
                        EntityPK = maj.mjPrimaryKey,
                        Name = maj.name, 
                        Type = "Maj"
                    };

var minorClients = from min in dbContext.MinorClients
                   where min.startdate > startDate
                        && min.status == "Active" || min.status== "Inactive"
                        && !(from maj in dbContext.MajorClients
                             where maj.startdate > startDate
                                && maj.status == "Active"
                             select maj.name).Contains(min.Name)
                   select new Client
                        {
                            EntityPK = min.mnPrimaryKey,
                            Name = min.name, 
                            Type = "Min"
                        };

var allClients = majorClients.Union(minorClients);