c# - 具有其他实体作为属性的实体的 EF Core 实体发布错误
问题描述
情况:
- 用于发布新活动的 Code First C# Azure 函数
- Activity 有 Id、Helper 和 Round。最后两个也是实体,即 FK
- 数据库是 Azure SQL
- 虽然我可以发布新的助手和回合,但在使用现有的助手和回合发布新活动时...我收到此错误:
Executed 'ActivitysPost' (Failed, Id=a2e8a556-7b1b-4d0d-995c-65b9c494c802, Duration=26938ms)
[2021-05-03T05:04:29.141Z] System.Private.CoreLib: Exception while executing function: ActivitysPost.
Microsoft.EntityFrameworkCore.Relational: An error occurred while updating the entries.
See the inner exception for details.
Core .Net SqlClient Data Provider:
Cannot insert explicit value for identity column in table 'Helpers'
... when IDENTITY_INSERT is set to OFF.
错误发生在第 2 行:
_context.Add(activity);
await _context.SaveChangesAsync();
使用 EF Core 3.1.14
GitHub 项目(请参阅 API):https ://github.com/djaus2/mslearn-staticwebsite-3entities
注意:以下确实有效(即提交新的助手和回合):
curl --header "Content-Type: application/json" --request POST --data "{'Name':'Recording','Quantity':1,'Round':{'No':1,'Description':'AVSL'},'Helper':{'Name':'FreedyFeelgood','Description':'BlaBlah'}}" http://localhost:7071/api/activitys/
返回结果:
{"id":6,"name":"Recording","quantity":1,"helper":{"id":13,"name":"FreedyFeelgood","description":"BlaBlah"},"round":{"id":7,"no":1,"description":"AVSL"}}
解决方案
好的,所以查看代码,您遇到的问题是 ef 无法识别作为已在数据库中的实体附加的助手(和回合),而是将它们视为需要创建的新实体。
您可以通过附加从 api 调用反序列化的 Round 和 Helper 来解决此问题。
[FunctionName("ActivitysPost")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "activitys")] HttpRequest req,
ILogger log)
{
var body = await new StreamReader(req.Body).ReadToEndAsync();
var activity = JsonConvert.DeserializeObject<Activity>(body);
....
_context.Attach(activity.Helper); // <-- new
_context.Attach(activity.Round); // <-- new
await _context.SaveChangesAsync();
return new OkObjectResult(activity);
}
这告诉 ef 假设它们来自数据库,因此您不需要创建它们。PUT 方法也会有同样的问题,所以要小心。
希望这可以解决您的问题。
推荐阅读
- sql - SQL Server 性能问题
- mysql - 如何修复 500(内部服务器错误)?
- android - Kotlin:具有关联值的枚举;“枚举条目”中的函数得到“未解决的引用”错误
- java - 使用动态ip更改本地主机时如何访问MySQL本地服务器,错误类文件编辑器
- javascript - 我在 JavaScript 中应用 .map 函数时引用的原始对象
- python - Numpy:将方阵的索引转换为其上三角索引的有效方法
- android - OnTouchListerner 不应将滑动打开 DrawerLayout 解释为长按
- sql - Oracle 使用单个查询更新和更改两个表中的少量列记录
- mysql - 包含变量和 SELECT FROM 的 INSERT INTO 表名
- python - 如何以接近零的成本部署 jupyter notebook 应用程序