我在SQL Server中有这个查询:
SELECT 'QueueA', COUNT(*) FROM QueueA_Table
UNION
SELECT 'QueueB', COUNT(*) FROM QueueB_Table
如何使用Entity Framework执行等效操作?我能做的最好的是:
using (var db = new dbContext())
{
return new QueueCount[] {
new QueueCount("QueueA", db.QueueA_Table.Count()),
new QueueCount("QueueB", db.QueueB_Table.Count())
};
}
但是,根据LINQPad,这会导致两个单独的查询到数据库。
SELECT COUNT(*) AS [value]
FROM [QueueA_Table] AS [t0]
GO
SELECT COUNT(*) AS [value]
FROM [QueueB_Table] AS [t0]
有没有办法编写它以便只向数据库发送一个查询?
答案 0 :(得分:1)
可能不是最漂亮或最可维护的方式:
db.Database.SqlQuery<int>(@"
SELECT COUNT(*) FROM QueueA_Table
UNION
SELECT COUNT(*) FROM QueueB_Table");
或者如果你想填充一个类:
public class QueueCount
{
public string Name { get; set; }
public int Count { get; set; }
}
db.Database.SqlQuery<QueueCount>(@"
SELECT [Name] = 'QueueA', [Count] = COUNT(*) FROM QueueA_Table
UNION
SELECT [Name] = 'QueueB', [Count] = COUNT(*) FROM QueueB_Table");
答案 1 :(得分:0)
查询很难看,而且非常糟糕:
(from s in QueueA_Table.Take(1)
select new List<int> {
QueueA_Table.Count(),
QueueB_Table.Count()
}).First()
或
(from s in QueueA_Table.Take(1)
select new {
QueueA = QueueA_Table.Count(),
QueueB = QueueB_Table.Count()
})