处理级联多对多EF核心?

时间:2019-01-15 18:40:18

标签: c# entity-framework entity-framework-core ef-core-2.1

我不确定如何正确设置表格,因此在尝试进行多对多操作时不会出现这样的错误。

System.Data.SqlClient.SqlException: 'Introducing FOREIGN KEY constraint 'FK_TableB_TableA_TableBId' on table 'TableB' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.'

我的模特

public class TableA
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<TableB> TableBs { get; set; }
}

public class TableB
{
    public int Id { get; set; }
    public int TableCId { get; set; }
    public virtual TableC TableC { get; set; }
    public int TableAId { get; set; }
    public virtual TableA TableA { get; set; }
}

 public class TableAConfig : IEntityTypeConfiguration<TableA>
{
    public void Configure(EntityTypeBuilder<TableA> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id).ValueGeneratedOnAdd();
        builder.Property(x => x.Name).HasMaxLength(100).IsRequired();
    }
}

 public class TableBConfig : IEntityTypeConfiguration<TableB>
{
    public void Configure(EntityTypeBuilder<TableB> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id).ValueGeneratedOnAdd();
    }
}

//code snippet

//remove all tableB
  company.TableBs.Clear();


// add all new dealers.
foreach (var d in dto.Data)
{
    company.TableBs.Add(new TableB() { TableCId = d.id, TableA = TableA });
}

   dbContext.SaveChanges();

编辑

 public class TableC
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }

    public virtual ICollection<TableBs> TableBs { get; set; }

}

    public class TableCConfig : IEntityTypeConfiguration<TableC>
{
    public void Configure(EntityTypeBuilder<TableC> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id).ValueGeneratedOnAdd();

        builder.Property(x => x.Name).HasMaxLength(50).IsRequired();
        builder.Property(x => x.Code).HasMaxLength(5).IsRequired();

    }
}

0 个答案:

没有答案