首页 > 解决方案 > EFCore:在 SaveChanges() 期间由于 fk 对象不存在而导致 fk 约束失败时该怎么办

问题描述

我应该如何处理不存在的关系?

我正在从 API 同步数据,并且收到一些错误数据:

因此,我创建了 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

我不确定我最好的选择是什么。

我不能保证来自 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; }
}

标签: c#entity-frameworksqliteentity-framework-core

解决方案


推荐阅读