我有一个 Entity Framework Core 模型,定义如下:
class User
{
public int ID;
public ICollection<Foo> OwnedFoos;
}
[PrimaryKey(nameof(ID), nameof(OwnerID))]
class Foo
{
public int ID;
public int OwnerID;
[ForeignKey("OwnerID")]
public User Owner;
}
class DerivedFoo : Foo
{
public int DerivedProp;
}
这会生成一个大致如下的模式(SQL 伪代码):
TABLE Users
COLUMN ID
TABLE Foos
COLUMN ID
COLUMN OwnerID
PRIMARY KEY (ID, OwnerID)
FOREIGN KEY OwnerID -> User.ID ON CASCADE DELETE
TABLE DerivedFoos
COLUMN ID
COLUMN OwnerID
COLUMN DerivedProp
FOREIGN KEY OwnerID -> Users.ID ON CASCADE DELETE
FOREIGN KEY (ID, OwnerID) -> (Foos.ID, Foos.OwnerID) ON CASCADE DELETE
当我尝试在 SQL Server 中生成数据库时,这会导致错误,因为它包含多个级联删除路径。我可以使用 Fluent API 删除导出->基本 CASCADE DELETE 子句,但我真正想做的是通过从导出类型表中删除 Users FK 将架构修改为以下内容。
TABLE Users
COLUMN ID
TABLE Foos
COLUMN ID
COLUMN OwnerID
PRIMARY KEY (ID, OwnerID)
FOREIGN KEY OwnerID -> User.ID ON CASCADE DELETE
TABLE DerivedFoos
COLUMN ID
COLUMN OwnerID
COLUMN DerivedProp
FOREIGN KEY (ID, OwnerID) -> (Foos.ID, Foos.OwnerID) ON CASCADE DELETE
但是,当我尝试使用
Ignore()
删除此关系时,EF 工具会抛出错误,因为该关系是在基本类型上定义的。有没有办法无需人工干预即可实现所需的架构?
如果你使用FluentAPI,你可以做类似的事情。 我认为数据注释更具挑战性。 您可能需要为其编写自定义 SQL。
{
modelBuilder.Entity<DerivedFoo>()
.HasMany(p => p.User)
.OnDelete(DeleteBehavior.Restrict); // This turns off cascade delete
}