把.netcore 2.2升级到3.1后,EFcore里,执行自己写的sql一直报错。部分代码如下:
//using System.Data.SqlClient;
List<SmallOrderResp> result = new List<SmallOrderResp>(); string sql = @"select * from cs_orders"; SqlParameter[] parameters = { new SqlParameter("@app_user_id",app_user_id) }; result= this.QueryBySql<SmallOrderResp>(sql, parameters).ToList();
/// <summary> /// 执行SQL查询-返回List /// </summary> public virtual IEnumerable<Entity> QueryBySql<Entity>(string sql, object[] parameters = null) { DbConnection connection = _dbContext.Database.GetDbConnection(); DbCommand cmd = connection.CreateCommand(); connection.Open(); cmd.CommandText = sql; cmd.CommandType = CommandType.Text; if (parameters != null) { cmd.Parameters.AddRange(parameters); } DataTable dt = new DataTable(); using (DbDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); cmd.Parameters.Clear(); } connection.Close(); return ConvertHelper.DataTableToIList<Entity>(dt).ToList(); }
简单的错误信息如下:
The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects.
详细信息如下:
at Microsoft.Data.SqlClient.SqlParameterCollection.ValidateType(Object value) at Microsoft.Data.SqlClient.SqlParameterCollection.AddRange(Array values) at MuXue.Zyiz.Template.Infrastructure.Repository.BaseRepository`1.QueryBySql[Entity](String sql, Object[] parameters) in D:\VSWrok\MuXue.Zyiz.Template.WebApi\MuXue.Zyiz.Template.Infrastructure\Repository\BaseRepository.cs:line 609 at MuXue.Zyiz.Template.Infrastructure.Repository.ordersRepository.<QueryListSmallModel>d__1.MoveNext() in D:\VSWrok\MuXue.Zyiz.Template.WebApi\MuXue.Zyiz.Template.Infrastructure\Repository\ordersRepository.cs:line 38 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at MuXue.Zyiz.Template.Service.Impl.ordersService.<GetList>d__9.MoveNext() in D:\VSWrok\MuXue.Zyiz.Template.WebApi\MuXue.Zyiz.Template.Service\Impl\ordersService.cs:line 63
找了很长时间一直未找到解决方案,最终在github上找到问题所在:
https://github.com/dotnet/efcore/issues/16812
原来是
using System.Data.SqlClient;
这个的错误,.netcore 3.1以后,就不能用这个了。需要用另一个,如下。
Microsoft.Data.SqlClient