3

有人可以帮助我以正确的方式将此查询转换为 Linq 到实体查询。我对 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
4

3 回答 3

1

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

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});
于 2012-04-05T14:34:52.353 回答
0
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})
于 2012-04-05T14:36:11.247 回答
0

我知道这是一个老问题,但我想我会加两分钱,希望我可以为那些认为我最初认为 Union() 是正确使用方法的人节省一些时间。

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

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);
于 2019-05-03T00:18:48.357 回答