ASP.Net 使用存储过程时出现 Core 3.1 MVC 错误

ASP.Net Core 3.1 MVC Error while using stored procedures

客户希望所有与数据库的通信都通过存储过程完成。要在 ASP 中执行此操作,我会像这样使用 FromSqlRaw:

_context.Visit.FromSqlRaw("exec VisitApi_RecordVisit @User", userParam)

存储过程执行其工作并记录访问。但是每次它触发时都会在控制台中抛出错误:

System.InvalidOperationException: The required column 'Id' was not present in the results of a 'FromSql' operation.

在研究这个错误时我发现这个错误是因为它正在记录的 table 有一个主键。要解决此问题,我必须删除主键列,然后将其添加回来,并将“身份规范”设置为“否”。我也尝试添加 .HasNoKey();到 table 并尝试更新数据库。但是,当我这样做时,它告诉我需要删除该列并再次将其添加回去。问题是已经记录了大约 200,000 次访问,我不想丢失已经绑定到每一行的 ID。有什么方法可以让我在不删除列和/或删除现有数据的情况下摆脱这个错误?

您也可以使用:

using(var context = new SampleContext())
{
    var name = new SqlParameter("@CategoryName", "Test");
    context.Database.ExecuteSqlCommand("EXEC AddCategory @CategoryName", name);
}

(取自https://www.learnentityframeworkcore.com/raw-sql#database.executesqlcommand

文档:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.database?view=efcore-3.1

https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.executesqlcommand?view=efcore-3.1