.netcore 3.1 EFCore报错-The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects.
把.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
作者:沐雪
文章均系作者原创或翻译,如有错误不妥之处,欢迎各位批评指正。本文版权归作者和博客园共有,如需转载恳请注明。
如果您觉得阅读这篇博客让你有所收获,请点击右下方【推荐】
为之网-热爱软件编程 http://www.weizhi.cc/