温馨提示:本文翻译自stackoverflow.com,查看原文请点击:entity framework core - EFCore DbConnection.CreateCommand parameters not passing
entity-framework-core

entity framework core - EFCore DbConnection.CreateCommand参数未通过

发布于 2020-04-05 20:34:36

我在我的项目中使用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则不会返回任何行

查看更多

提问者
Alex Kibler
被浏览
64
Ricardo Peres 2020-01-31 23:44

该参数不能包含在'内,否则不会被检测为参数。使用此代替:

command.CommandText = @"select * from customers where customerName = @customerName";