所以这里有几个类似的问题,但我仍然无法确定在我的简化场景中到底缺少什么。
假设我有以下表格,巧妙地以我自己的名字命名:
'JohnsParentTable' (Id, Description)
'JohnsChildTable' (Id, JohnsParentTableId, Description)
生成的类看起来像这样
public class JohnsParentTable
{
public int Id { get; set; }
public string Description { get; set; }
public virtual ICollection<JohnsChildTable> JohnsChildTable { get; set; }
public JohnsParentTable()
{
JohnsChildTable = new List<JohnsChildTable>();
}
}
internal class JohnsParentTableConfiguration : EntityTypeConfiguration<JohnsParentTable>
{
public JohnsParentTableConfiguration()
{
ToTable("dbo.JohnsParentTable");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Description).HasColumnName("Description").IsRequired().HasMaxLength(50);
}
}
public class JohnsChildTable
{
public int Id { get; set; }
public string Description { get; set; }
public int JohnsParentTableId { get; set; }
public JohnsParentTable JohnsParentTable { get; set; }
}
internal class JohnsChildTableConfiguration : EntityTypeConfiguration<JohnsChildTable>
{
public JohnsChildTableConfiguration()
{
ToTable("dbo.JohnsChildTable");
HasKey(x => x.Id);
Property(x => x.Id).HasColumnName("Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Description).HasColumnName("Description").IsRequired().HasMaxLength(50);
HasRequired(a => a.JohnsParentTable).WithMany(c => c.JohnsChildTable).HasForeignKey(a => a.JohnsParentTableId);
}
}
在数据库中,我在父表中有一行 ID 为 1,在子表中有两行与该父表关联。如果我这样做:
var parent = db.JohnsParentTable.FirstOrDefault(a => a.Id == 1)
对象已正确填充。但是,如果我尝试删除这一行:
var parent = new Data.Models.JohnsParentTable() { Id = 1 };
db.JohnsParentTable.Attach(parent);
db.JohnsParentTable.Remove(parent);
db.SaveChanges();
Entity Framework 尝试执行以下操作:
DELETE [dbo].[JohnsParentTable]
WHERE ([Id] = @0)
-- @0: '1' (Type = Int32)
-- Executing at 1/23/2014 10:34:01 AM -06:00
-- Failed in 103 ms with error: The DELETE statement conflicted with the REFERENCE constraint "FK_JohnsChildTable_JohnsParentTable". The conflict occurred in database "mydatabase", table "dbo.JohnsChildTable", column 'JohnsParentTableId'.
The statement has been terminated.
那么我的问题是,我到底缺少什么来确保 Entity Framework 知道它必须在删除父级之前删除“JohnsChildTable”行?
最佳答案
我认为最好重写 OnModelCreating 方法并添加这段代码。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<JohnsChildTable>()
.HasRequired(t=>t.JohnsParentTable)
.WithMany(t=>t.JohnsChildTables)
.HasForeignKey(d=>d.JohnsParentTableId)
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
我已经设置为 true WillCascadeOnDelete(true)
关于c# - Entity Framework 6 : Code First Cascade delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21314113/