繁体   English   中英

实体框架核心FromSQL引发ArgumentNullException

[英]Entity Framework core FromSQL throws ArgumentNullException

我正在使用C#(.net core v2.2)和EF core。 我有很旧的代码正在从数据库中检索一行:

string id = "123";
using (var context = new UsersDb())
{
    var req = context.ScanRequests.FromSql($"EXEC GetById {id}").FirstOrDefault();
    // ...
}

GetById是一个存储过程,用Azure SQL(基本上是SQL Server)编写。

这段代码最近开始引发异常:

System.ArgumentNullException: Value cannot be null.
Parameter name: key
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at lambda_method(Closure , ServiceProviderEngineScope )
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
   at Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql[TEntity](IQueryable`1 source, FormattableString sql)
   at ***.***Factory.<>c__DisplayClass0_0.<GetById>b__0() in /tmp/sources/SystemLayer/***/***.cs:line 29

当我在本地环境中使用相同的参数运行相同的代码时,不会发生此问题。 而且,在大多数情况下,它也可以在生产服务器上运行。 我猜它的成功率至少为99.9%。

更新1

为了确定哪一行是有问题的(创建进程或运行FromSql方法),我添加了一条日志消息,并确定问题出在下面这样:

var req = context.ScanRequests.FromSql($"EXEC GetById {id}").FirstOrDefault();

更新2

我以为问题可能是由于我到数据库的映射-也许数据库模式已更改而未相应更改EF。 因此,我再次运行映射命令:

Scaffold-DbContext "cs" ...

再次重新生成类后,我发现自上次提交GIT以来,没有文件已更改。 因此,我的EF代码已经与数据库架构对齐。

更新3

我使用EF Nuget软件包2.2.1版运行代码。 我看到可以将EF软件包更新为2.2.2。 我做到了,但没有解决问题。 行为相同。

该怎么办? 我还应该检查什么?

您可能假设$"EXEC GetById {id}"是一个string ,但实际上是一个FormattableString ,如堆栈跟踪所示:

at Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql[TEntity](IQueryable`1 source, FormattableString sql)

因此,您不小心调用了另一种方法。 尝试向string添加显式强制转换以执行所需的强制转换:

var req = context.ScanRequests.FromSql((string)$"EXEC GetById {id}").FirstOrDefault();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM