将一个项目从 .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)
请问如何解决?
在 github 上找到了解决方法:
Fixed by changing
using System.Data.SqlClient
tousing Microsoft.Data.SqlClient
详见 The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects
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 创建一个参数化的查询,其中参数是从查询字符串中单独传递的。