【问题标题】:ASP.Net Core 3.1 MVC Error while using stored procedures使用存储过程时出现 ASP.Net Core 3.1 MVC 错误
【发布时间】:2021-08-26 15:09:47
【问题描述】:

客户端希望通过存储过程完成与数据库的所有通信。要在 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.

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

【问题讨论】:

  • 为什么选择 Entity.FromSqlRaw() 来运行任意 Sql proc?
  • 使用 context.Database.ExecuteSqlCommand("EXEC AddCategory @CategoryName", name);

标签: c# sql asp.net asp.net-mvc asp.net-core-3.1


【解决方案1】:

您也可以使用:

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

【讨论】:

  • 在这种情况下,'new SampleContext()' 会是什么?
  • 您的 DbContext。如果它已经创建/取自 DI,则无需再次创建。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多