1

我一直在尝试将准备好的语句合并到我使用 EF 5.0 的应用程序中。请看下面我的脚本。

int parameterValue = 100000;
var addParameters = new List<MySqlParameter>();
var param1 = new MySqlParameter();
param1.Direction = System.Data.ParameterDirection.Input;
param1.Value = parameterValue;
param1.ParameterName = "user_id";
addParameters.Add(param1);
db.Database.ExecuteSqlCommand(@"delete FROM tbl_user where user_id = @user_id", addParameters);

它产生这个错误

Exception: {"Fatal error encountered during command execution."}
InnerException: {"Parameter '@user_id' must be defined."}

所以基于 InnerException 描述我将参数 nae 更改为“@user_id”

int parameterValue = 100000;
var addParameters = new List<MySqlParameter>();
var param1 = new MySqlParameter();
param1.Direction = System.Data.ParameterDirection.Input;
param1.Value = parameterValue;
param1.ParameterName = "@user_id";
addParameters.Add(param1);
db.Database.ExecuteSqlCommand(@"delete FROM tbl_user where user_id = @user_id", addParameters);

但仍然是同样的错误。

我可能做错了什么?

提前致谢。

================================================ 附加信息

<package id="EntityFramework" version="5.0.0" targetFramework="net40" />
<package id="MySql.Data" version="6.7.4" targetFramework="net40" />
<package id="MySQL.Data.Entities" version="6.7.4.1" targetFramework="net40" />
4

2 回答 2

0

让我向您展示一些好的实践代码,这些代码展示了您想要什么 + 资源释放建议:

using (SqlCommand comm = conn.CreateCommand()) //release good practice
{
    comm.CommandText = "delete FROM tbl_user where user_id = @user_id";
    comm.CommandType = CommandType.Text; //can be skipped for your case
    comm.Parameters.Add(new SqlParameter("@user_id", SqlDbType.Int)).Value =
        parameterValue;
    comm.ExecuteNonQuery();
}
于 2013-08-10T17:01:09.673 回答
0

由于您使用的是 EF,我认为您应该使用以下内容:

int parameterValue = 100000;
db.Database.ExecuteSqlCommand(@"delete FROM tbl_user where user_id = {0}", parameterValue);
于 2020-03-02T11:56:46.903 回答