将联合查询转换为LINQ转换为实体查询

本文关键字:转换 查询 实体 LINQ | 更新日期: 2023-09-27 18:30:03

有人能帮助我以正确的方式将此查询转换为Linq-to-entities查询吗。我是Linq的新手,希望正确地编写这些查询。这是一个相当涉及我对UNION和中的子查询所做的事情

SELECT pf.FileID, pf.ServerName, pf.MigrationType 
FROM pOrders pf 
WHERE pf.FileID IN (select GCMFileID FROM Signals
                    where SignalFileID = " + FileID + ")
UNION 
SELECT pf.FileID, pf.ServerName, pf.MigrationType
FROM pOrders pf 
WHERE pf.FileID = " + FileID + "
order by pf.MigrationType desc

将联合查询转换为LINQ转换为实体查询

我知道,我看到了评论。。。但是

var signalIds = Signals.Where(s => s.SignalFileId = FILEID).Select(x => x.GCMFileID ).ToArray();
pOrders.Where(pf => signalIds.Contains(pf.FileID))
.Union(
pOrders.Where(pf => pf.FileID == FILEID))
.OrderByDescending(u => u.MigrationType)
.Select(u => new {u.FileID, u.ServerName, u.MigrationType});
var innerquery = from t in db.Signals
                 where t.SignalFileID == FileID
                 select new {t.SignalFieldID};
var query = (from p in db.pOrders
            where p.FieldID.Contains(innerquery.SignalFieldID)
            select new {p.FileID, p.ServerName, p.MigrationType}).Union
            (from p in db.pOrders
            where p.FieldID ==FieldID
            orderby p.MigrationType
            select new {p.FileID, p.ServerName, p.MigrationType})

我知道这是一个老问题,但我想我应该加上我的两美分,希望我能为那些像我最初那样认为Union()是正确方法的人节省一些时间。

我的第一个失误是,在遇到第一个错误,即xml列类型不能在distinct中使用后,用实体的逻辑键创建了一个自定义比较器。然后,Linq to Entities抱怨它不承认Union()。我注意到已接受的答案调用ToArray。这会在执行并集之前将第一个查询的全部结果带入内存。OP想要Linq到实体,所以你需要对IQueryable采取行动。使用Concat。整个查询将在数据库中运行。

var innerquery = (from t in db.Signals
             where t.SignalFileID == FileID
             select t.SignalFileID);
var query = (from p in db.pOrders
        where innerquery.Contains(p.FileID)
        select new {p.FileID, p.ServerName, p.MigrationType})
    .Concat(from p in db.pOrders
        where p.FileID == FileID
        select new {p.FileID, p.ServerName, p.MigrationType})
    .OrderBy(o => o.MigrationType);