首页 新闻 会员 周边

EF Core 3.0 问题:"The SqlParameterCollection only accepts non-null SqlParameter type objects"

0
悬赏园豆:50 [已解决问题] 解决于 2019-10-06 21:58

将一个项目从 .NET Core 2.2 升级至 .NET Core 3.0 之后,下面的代码

var isOk = await Context.Database.ExecuteSqlRawAsync(
    "...",
    new SqlParameter("@UserID", userId)) > 0;

运行时报错

System.InvalidCastException: 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.Add(Object value)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RawRelationalParameter.AddDbParameter(DbCommand command, Object value)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.CreateCommand(RelationalCommandParameterObject parameterObject, Guid commandId, DbCommandMethod commandMethod)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQueryAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRawAsync(DatabaseFacade databaseFacade, String sql, IEnumerable`1 parameters, CancellationToken cancellationToken)

请问如何解决?

dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2019-10-06 14:55
< >
分享
最佳答案
0

在 github 上找到了解决方法:

Fixed by changing using System.Data.SqlClient to using Microsoft.Data.SqlClient

详见 The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects

dudu | 高人七级 |园豆:30994 | 2019-10-06 21:57
其他回答(1)
0

https://docs.microsoft.com/zh-cn/ef/core/what-is-new/ef-core-3.0/breaking-changes
FromSql、ExecuteSql 和 ExecuteSqlAsync 已重命名
跟踪问题 #10996

旧行为
在 EF Core 3.0 之前,这些方法名称是重载的,它们使用普通字符串或应内插到 SQL 和参数中的字符串。
新行为
自 EF Core 3.0 起,可使用 FromSqlRaw、ExecuteSqlRaw 和 ExecuteSqlRawAsync 创建一个参数化的查询,其中参数是从查询字符串中单独传递的。

收获园豆:50
landv | 园豆:287 (菜鸟二级) | 2019-10-06 16:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册