我在我的项目中使用EFCore,并且尝试执行原始SQL查询(因为我的目标是我不拥有的数据库,也不想为它建立大规模的架构),在参数中。这是我正在做的事情(尽管我已经更改了保护查询):
var customerId = "testname";
using (var command = _dbContext.Database.GetDbConnection().CreateCommand())
{
command.CommandText = @"select * from customers where customerName = '@customerName'";
var customerIdParam = new SqlParameter("@customerName", customerId);
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@customerName";
parameter.Value = customerId;
parameter.DbType = System.Data.DbType.String;
parameter.Direction = System.Data.ParameterDirection.Input;
command.Parameters.Add(parameter);
await _dbContext.Database.OpenConnectionAsync();
using (var result = await command.ExecuteReaderAsync())
{
return result;
}
}
问题在于该参数似乎没有传入。如果我对要发送的customerName的值进行硬编码,则该函数可以正常工作并返回行,但是如果我将其作为参数传入,result
则不会返回任何行
该参数不能包含在'内,否则不会被检测为参数。使用此代替:
command.CommandText = @"select * from customers where customerName = @customerName";
啊哈,就是这样!非常感谢。自上次我不得不在C#中执行原始SQL而不是使用ORM来处理它以来,已经过去了5年。