因此,在这里有几个类似的问题,但我仍然有问题,以确定我在我的简化方案中错过了什么。实体框架6:代码第一级联删除
比方说,我有以下表,照顾好自己巧妙地命名为:
'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();
实体框架尝试执行以下操作:
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.
那么我的问题是,究竟是什么我缺少保证实体框架知道它必须删除删除父项之前的'JohnsChildTable'行?
的OP问题是代码第一位。此解决方案仅适用于Model First。 – vidalsasoon