DbContext.Save on on sub on sub object 会引发“检测到冲突的更改”

本文关键字:on sub 冲突 检测 object Save DbContext | 更新日期: 2023-09-27 18:32:10

我有一个父/子层次结构,我想在其中插入一个新的父级到 DbContext 中,并让它自动保留子对象。该关系是一对多关系,其中每个父级可以在 0 列或更多列处。

但是每当我调用 DbContext.Save(parent) 时,我都会收到"检测到冲突的更改。尝试插入具有相同键的多个实体时可能会发生这种情况。当我剥离子列的父列时,它会节省罚款,所以我假设这与子对象没有设置主键有关。如何告诉实体框架正确保存我的层次结构?

我的课程:

public class ExcelTemplate
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int FirstDataRow { get; set; }
    public virtual ICollection<TemplateColumn> Columns { get; set; }
    public ExcelTemplate()
    {
        Columns = new List<TemplateColumn>();
    }
}
public class TemplateColumn
{
    public int Id { get; set; }
    public int Index { get; set; }
    public int MetricTypeId { get; set; }
    public virtual MetricType MetricType { get; set; }
    public int TemplateId { get; set; }
    public virtual ExcelTemplate Template { get; set; }
}

和配置:

public class ExcelTemplateConfiguration : EntityTypeConfiguration<ExcelTemplate>
{
    public ExcelTemplateConfiguration()
    {
        HasKey(t => t.Id)
            .Property(t => t.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(t => t.Name)
            .IsRequired();
        HasMany(t => t.Columns)
            .WithRequired(c => c.Template)
            .HasForeignKey(c => c.TemplateId);
    }
}
public class TemplateColumnConfiguration : EntityTypeConfiguration<TemplateColumn>
{
    public TemplateColumnConfiguration()
    {
        HasKey(c => c.Id)
            .Property(c => c.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(tpl => tpl.MetricType)
            .WithRequiredDependent();
    }
}

DbContext.Save on on sub on sub object 会引发“检测到冲突的更改”

  1. ExcelTemplate.IdTemplateColumn.Id是否有标识规范?是否正确设置了Id属性?

  2. 是否将TemplateColumn对象的 ExcelTemplate 属性设置为ExcelTemplate父级?

像这样:

ExcelTemplate t = new ExcelTemplate();
//init template code...skip
TemplateColumn c = new TemplateColumn();
//init template column code...skip
c.ExcelTemplate = t;//this is the line I am asking if you are doing. 

我通过反复试验发现了罪魁祸首,因为当我只尝试单独存储模板列时,问题仍然存在。

问题是从 TemplateColumn 配置中删除这行代码,并让实体框架按约定映射:

HasRequired(tpl => tpl.MetricType)
    .WithRequiredDependent();

知道为什么这不起作用吗?