Warm tip: This article is reproduced from stackoverflow.com, please click
entity-framework-core

EFCore DbConnection.CreateCommand parameters not passing

发布于 2020-04-05 00:26:28

I'm using EFCore in my project, and I'm attempting to execute a raw SQL query (because I'm targeting a database that I don't own and don't want to scaffold out the massive schema for it), passing in a parameter. Here is what I'm doing (although I've changed the query for protection):

            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;
                }
            }

The problem is that the parameter doesn't seem to be passing in. If I hardcode the value for customerName that I'm sending in, it works just fine and returns rows, but if I pass it in as a parameter, result doesn't return any rows

Questioner
Alex Kibler
Viewed
66
Ricardo Peres 2020-01-31 23:44

The parameter must not be enclosed inside ', otherwise it is not detected as a parameter. Use this instead:

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