c# - EFCore:在 SaveChanges() 期间由于 fk 对象不存在而导致 fk 约束失败时该怎么办
问题描述
我应该如何处理不存在的关系?
我正在从 API 同步数据,并且收到一些错误数据:
A 有孩子 B(B 对 A 有 FK)
我收到一个具有 AId 的 dto B,但此 A 在 A dto 集中不存在。
因此,我创建了 A 实体,然后在 EFCore 中创建 B 实体时,它使用影子属性在使用Entry.PropertyValues.SetValues(dto)
. 最后,当调用 SaveChanges() 时,SQLite 19 Foreign Key Constraint Failed
由于 A 不存在,我得到一个异常。
我的通用添加代码
//Setup the DBContext...
var newT = new T();
var entry = context.Add(newT);
entry.CurrentValues.SetValues(TDto); //It automatically sets the AId here while adding B entities
我不确定我最好的选择是什么。
我可以在创建 B 的过程中检查 A 是否存在,但这只是一个简单的示例,在我的实际情况中,需要检查许多这样的关系。
我要添加新实体完全错误吗?有一个通用的 add 方法会很好,也许我需要某种回调来对每个实体类型进行自定义检查?
我不能保证来自 API 的数据是安全的。
Dtos
public class ADto
{
public Guid Id { get; set; }
}
public class BDto
{
public Guid Id { get; set; }
public Guid AId { get; set; }
}
实体类
public class A
{
public Guid Id { get; set; }
public virtual Collection<B> children { get; set; }
}
public class B
{
public Guid Id { get; set; }
public Guid AId { get; set; }
public virtual A { get; set; }
}
解决方案
推荐阅读
- html - 包裹在 p 和 h HTML 标记内时,shiny::textOutput 的不同行为
- python - Python 从 bitbucket 读取配置文件
- r - 如何重塑数据结构
- python - Nginx/Gunicorn/python/matlab 运行时,Worker 无法启动
- amazon-web-services - 如何使用 Datadog 监控失败的 AWS EMR 步骤
- string - 运行时构建:在此范围内找不到字符串
- firebase - 使用“firebase init”安装 Firebase 功能模拟器后如何卸载它
- node.js - 在存储位置找不到存档:Google 函数
- javascript - 我正在尝试运行此反应本机屏幕,它会为我获取数据。当我从主屏幕单击文本时,它会运行。但它不工作
- autocad - 导入obj文件并添加纹理