【发布时间】:2011-09-28 19:49:38
【问题描述】:
问题:如何让 EF 4.1 使用 fluent api 为基表指定外键约束上的 ON DELETE CASCADE 选项?我知道如何处理与其他表的关系,但我如何让它为 TPT(每个类型的表)表生成这个?
说明:
让我指出,我指的不是外键关系。对于我的 DbContext,我总是为我的实体使用 Mapping 对象,只是因为在大多数情况下,我更喜欢明确而不是接受约定方法。话虽如此,我的 TPT 表的所有配置都在 EntityTypeConfiguration<SomeEntityClass> 类中处理。
当我通过创建从另一个派生的新类来定义 TPT 关系时,ON DELETE CASCADE 不会在 SQL 约束中生成,这就是问题所在。
看看下面的代码...
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
}
public class OtherPerson : Person
{
public string SomeOtherProperty { get; set; }
}
public class PersonMap : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Person>
{
public PersonMap()
{
this.HasKey(t => t.PersonId); // Primary Key
this.Property(t => t.PersonId)
.HasColumnName("PersonId") // Explicitly set column name
.IsRequired() // Field is required / NOT NULL
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); // Specify as Identity (Not necessary, but I'm explicit)
this.Property(t => t.Name)
.HasColumnName("Name") // Explicitly set column name
.IsRequired() // Field is required / NOT NULL
.HasMaxLength(50); // Max Length
this.ToTable("People"); // Map to table name People
}
}
public class OtherPersonMap : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<OtherPerson>
{
public OtherPersonMap()
{
this.Property(t => t.SomeOtherProperty)
.HasColumnName("SomeOtherProperty") // Explicitly set column name
.IsRequired() // Field is required / NOT NULL
.HasMaxLength(10); // Max Length
this.ToTable("OtherPeople"); /* Map to table name OtherPeople
* This also causes TPT to create a shared primary key from the base table
* and double serving as a foreign key to base table.
*/
}
上面的代码真的很简单。我有 2 种类型,它们在数据库中正确创建。如果我创建一个新的OtherPerson 并保存到数据库,它会正确创建 2 条记录,第一条记录在 People 表中,另一条在 OtherPeople 表中,共享主键也是 OtherPeople 的外键人们。
现在,如果我在代码中删除 OtherPerson,则 DbContext 或 EF 会正确删除两条记录。但是,如果我直接从数据库中删除记录,People 表中会留下一条孤立记录。
那么,如何为使用 fluent api 为基表生成的外键约束指定 ON DELETE CASCADE?
对不起,这个问题太长了,但我只是想尽可能地描述我的问题。 提前致谢。
【问题讨论】:
标签: c# entity-framework-4.1 ef-code-first code-first fluent-interface