如何使用 mysql 使用输入和输出参数调用 Entity Framework Core 中的存储过程

How to call stored procedure in Entity Framework Core with input and output parameters using mysql

我正在使用 ASP.net Core 2.2 与 Entity Framework core 2.2.6 和 Pomelo.EntityFrameworkCore.MySql 2.2.0 连接 MySQL,我有一个存储过程需要3个输入参数和1个输出参数。我可以在 MySQL workbench 中调用它,比如

CALL GetTechniciansByTrade('Automobile', 1, 10, @total);
select @total;

现在我想用entity framework核心调用这个,我现在使用的代码是

var outputParameter = new MySqlParameter("@PageCount", MySqlDbType.Int32);
outputParameter.Direction = System.Data.ParameterDirection.Output;

var results = await _context.GetTechnicians.FromSql("Call GetTechniciansByTrade(@MyTrade, @PageIndex, @PageSize, @PageCount OUT)",
new MySqlParameter("@MyTrade", Trade),
new MySqlParameter("@PageIndex", PageIndex),
new MySqlParameter("@PageSize", PageSize),
outputParameter).ToListAsync();

int PageCount = (int)outputParameter.Value;

我目前得到的异常是

Only ParameterDirection.Input is supported when CommandType is Text (parameter name: @PageCount)

你能试试下面的东西吗?

  1. 使用 exec 而不是 call

    var 结果=等待_context.GetTechnicians.FromSql("EXEC GetTechniciansByTrade(@MyTrade, @PageIndex, @PageSize, @PageCount OUTPUT)"

  2. Select 存储过程中的 PageCount

我从这个 github issue.

得到了信息

我根据这个 Question 使用 @matt-g 建议找到了解决方案。 我不得不为此使用 ADO.net 作为

var technicians = new List<TechnicianModel>();
using (MySqlConnection lconn = new MySqlConnection(_context.Database.GetDbConnection().ConnectionString))
{
    lconn.Open();
    using (MySqlCommand cmd = new MySqlCommand())
    {
        cmd.Connection = lconn;
        cmd.CommandText = "GetTechniciansByTrade"; // The name of the Stored Proc
        cmd.CommandType = CommandType.StoredProcedure; // It is a Stored Proc

        cmd.Parameters.AddWithValue("@Trade", Trade);
        cmd.Parameters.AddWithValue("@PageIndex", PageIndex);
        cmd.Parameters.AddWithValue("@PageSize", PageSize);

        cmd.Parameters.AddWithValue("@PageCount", MySqlDbType.Int32);
        cmd.Parameters["@PageCount"].Direction = ParameterDirection.Output; // from System.Data

        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                technicians.Add(new TechnicianModel()
                {
                    City = reader["City"].ToString(),
                    ExperienceYears = reader["ExperienceYears"] != null ? Convert.ToInt32(reader["ExperienceYears"]) : 0,
                    Id = Guid.Parse(reader["Id"].ToString()),
                    Name = reader["Name"].ToString(),
                    Qualification = reader["Qualification"].ToString(),
                    Town = reader["Town"].ToString()
                });
            }
        }

        Object obj = cmd.Parameters["@PageCount"].Value;
        var lParam = (Int32)obj;    // more useful datatype
    }
}