Linq联合都相当于sql代码



我有以下查询:

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中表示这个查询?

试试这个链接。为了从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);

相关内容

  • 没有找到相关文章

最新更新