我在理解调用storedprocedure的FromSql子句时遇到了麻烦。 我想要实现的目标: 我想用用户名和密码查询用户。如果我输入正确的凭据,一切正常。 FromSql子句用值填充我的Object。好到目前为止。困扰我的是以下场景:如果我将应用程序重新启动并输入错误的凭据 第一次 ,我会遇到以下异常:
Microsoft.EntityFrameworkCore.Query:Error: An exception occurred in the database while iterating the results of a query for context type 'xyz.DatabaseContext'.
System.InvalidOperationException: The required column 'Id' was not present in the results of a 'FromSql' operation.
我也明白异常。如果没有找到用户,则存储过程返回0,并且EF尝试将此“空”结果映射到失败的对象中。
现在这里有一件奇怪的事情:如果我使用有效凭据的用户尝试使用 之后 输入错误的凭据,则不会发生异常。 queryResult的计数为0,这是预期的。这让我很困惑。为什么它在第一次“错误”尝试失败并且之后工作会返回成功的结果?
以下是storedprocedure的调用:
queryResult = await mDatabaseContext.MyModelObject
.FromSql($"myStoredProcedure {null}, {username}, {password}, {null}, {null}, {null}")
.OrderBy(x => x.ID).ToListAsync();
配置:
在Startup.cs
中,我将DatabaseContext添加为singleton
services.AddDbContext<DatabaseContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),
ServiceLifetime.Singleton);
我通过Dependency-Injection使用DatabaseContext,我调用上面描述的FromSql。
任何帮助都将不胜感激。
提前致谢!