EF Core ExecuteSqlCommandAsync:将 nvarchar 值“1,2”转换为数据类型 int 时转换失败

EF Core ExecuteSqlCommandAsync : Conversion failed when converting the nvarchar value '1,2' to data type int

我正在 运行ning 执行原始 sql 以删除我为测试添加的一些记录。如果我 运行 在 management studio 中使用相同的查询它工作正常但是当我 运行 查询 EF Core 2.0 时它抛出以下错误

System.Data.SqlClient.SqlException: 'Conversion failed when converting the nvarchar value '1,2' to data type int.'

代码

var idList = await Context.User.ToListAsync();
var ids = string.Join(",",idList.Select(x=>x.Id));
await _context.Database.ExecuteSqlCommandAsync($"Delete from User where Id in ({ids}) and RoleId = {contact.RoleId}");

查询正在执行 Delete from sale.WatchList where OfferId in (1,2) and UserId = 9

谁能告诉我上面的代码有什么问题。

谢谢

EF Core 会将内插字符串转换为带有参数的查询,以创建可重用查询并防止 SQL 注入漏洞。参见:Raw SQL Queries - EF Core - Passing Parameters

所以

$"Delete from User where Id in ({ids}) and RoleId = {contact.RoleId}"

转化为

   Delete from User where Id in (@ids) and RoleId = @RoleId

绑定了 SqlParameters。

如果这不是您想要的,只需在前一行构建 SQL 查询。

这行不通。您必须编写动态查询。请像下面一样尝试

var idList = await _dataContext.User.ToListAsync();
            var ids = string.Join(",", idList.Select(x => x.Id));
            await _dataContext.Database.ExecuteSqlCommandAsync($"execute('Delete from User where Id in ({ids}) and RoleId = {contact.RoleId}')");

虽然接受的答案确实有效,但它会产生很多警告,所以现在我正在使用@Abu Zafor 建议的小 change/fix

await _dataContext.Database.ExecuteSqlCommandAsync($"execute('Delete from User where Id in ({ids}) and RoleId = {contact.RoleId}')",ids,contact.RoleId);