由于 EF Core 当前不在数据库中执行分组查询,我使用以下查询来完成工作(InvoiceQuery
是 DbQuery
类型) :
long merchantId = 177;
var invTokens = new List<string> {"qasas", "efsac"};
string inClause = string.Join(",", invTokens);
string query = $@"SELECT i.Token, i.Balance, COALESCE(SUM(i.Amount), 0) AS ProcessingAmount
FROM inv.Invoices i
WHERE i.Token IN ({inClause})
AND i.MerchantId = {merchantId}
AND i.Status = {(int)InvoiceStatus.Scheduled}
GROUP BY i.Token, i.Balance";
return await dbContext.InvoicesQuery.FromSql(query).ToListAsync();
上面的代码运行完美,但我不喜欢它,因为它给我一个“可能的 SQL 注入(inject)漏洞”的警告。我知道我可以使用 #pragma
来抑制这个警告(这就是我目前正在使用的)。
我已经尝试传递查询并将参数提供给 FromSql
方法,这很有效,但是进入 IN
子句的参数没有得到正确映射。 .
尝试使用 $"'{string.Join("', '", invTokens)}'"
但没有成功。
任何帮助将不胜感激
最佳答案
从 EF Core 2.0 开始,您可以使用 FormattableString,您可以在其中使用字符串插值进行查询。
String interpolation in FromSql and ExecuteSqlCommand
FormattableString Class
In EF Core 2.0 we added special support for interpolated strings to our two primary APIs that accept raw SQL strings:
FromSql
andExecuteSqlCommand
. This new support allows C# string interpolation to be used in a 'safe' manner.
文档中的示例:
var city = "London";
var contactTitle = "Sales Representative";
using (var context = CreateContext())
{
context.Set<Customer>()
.FromSql($@"
SELECT *
FROM ""Customers""
WHERE ""City"" = {city} AND
""ContactTitle"" = {contactTitle}")
.ToArray();
}
这将产生:
@p0='London' (Size = 4000)
@p1='Sales Representative' (Size = 4000)
SELECT *
FROM ""Customers""
WHERE ""City"" = @p0
AND ""ContactTitle"" = @p1
关于c# - 如何避免在此 EF Core 查询中进行 SQL 注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55367514/