如何将SQL转成LINQ或其他方法
How to transfer SQL to LINQ or other methods
所以我一直在尝试执行查询。这是查询:
WITH ranked_loggings AS(
SELECT m.*, ROW_NUMBER() OVER(PARTITION BY proportioning_dbid ORDER BY logging_dbid DESC) AS rn
FROM logging AS m )
SELECT* FROM ranked_loggings WHERE rn = 1;
我试过很多解决方案,比如 http://www.sqltolinq.com/ and http://www.linqpad.net/。不幸的是,据我所知,这些不支持 PostgreSQL。现在我尝试原始执行查询。现在我无法获得结果并且我的应用程序不断崩溃。有人可以指出我正确的方向还是我在这里完全遗漏了什么?
想通了。显然不可能在没有参数的情况下使用原始 SQL 。是这样解决的:
using (var context = new AmadeusDBContext())
{
ICollection<Logging> loggings = context.Loggings
.FromSqlRaw("WITH ranked_loggings AS( " +
"SELECT m.*, ROW_NUMBER() OVER(PARTITION BY proportioning_dbid ORDER BY logging_dbid DESC) AS rn " +
"FROM logging AS m ) " +
"SELECT* FROM ranked_loggings WHERE rn = 1;", new NpgsqlParameter("@parameterrequired", 01))
.ToList<Logging>();
return loggings;
}
EF Core 应从此 LINQ 查询生成所需的结果:
var loggings = context.Loggings;
var query =
from d in loggings.Select(m => new { m.proportioning_dbid }).Distinct()
from m in loggings
.Where(m => m.proportioning_dbid == d.proportioning_dbid)
.OrderByDescending(m => m.logging_dbid)
.Take(1)
select m;
所以我一直在尝试执行查询。这是查询:
WITH ranked_loggings AS(
SELECT m.*, ROW_NUMBER() OVER(PARTITION BY proportioning_dbid ORDER BY logging_dbid DESC) AS rn
FROM logging AS m )
SELECT* FROM ranked_loggings WHERE rn = 1;
我试过很多解决方案,比如 http://www.sqltolinq.com/ and http://www.linqpad.net/。不幸的是,据我所知,这些不支持 PostgreSQL。现在我尝试原始执行查询。现在我无法获得结果并且我的应用程序不断崩溃。有人可以指出我正确的方向还是我在这里完全遗漏了什么?
想通了。显然不可能在没有参数的情况下使用原始 SQL 。是这样解决的:
using (var context = new AmadeusDBContext())
{
ICollection<Logging> loggings = context.Loggings
.FromSqlRaw("WITH ranked_loggings AS( " +
"SELECT m.*, ROW_NUMBER() OVER(PARTITION BY proportioning_dbid ORDER BY logging_dbid DESC) AS rn " +
"FROM logging AS m ) " +
"SELECT* FROM ranked_loggings WHERE rn = 1;", new NpgsqlParameter("@parameterrequired", 01))
.ToList<Logging>();
return loggings;
}
EF Core 应从此 LINQ 查询生成所需的结果:
var loggings = context.Loggings;
var query =
from d in loggings.Select(m => new { m.proportioning_dbid }).Distinct()
from m in loggings
.Where(m => m.proportioning_dbid == d.proportioning_dbid)
.OrderByDescending(m => m.logging_dbid)
.Take(1)
select m;