我已经阅读了关于stackoverflow上EF的外键问题及其建议解决方案的许多问题。但没有一个适合我的情况。
我有一个父类XSection
public class XSection
{
public int ObjectId {get; set;}
public OverBank LeftOverBank {get; set;}
public OverBank RightOverBank {get; set;}
}
overbanks是父Xsection类的子实体(只有一个不是列表)。 OverBanks类看起来像
public class OverBank
{
public int ObjectId {get; set;}
public int ParentId (get; set;}
public double Station {get; set;}
// some other basic properties
}
为上述类生成的DDL是:
CrossSection表:
CREATE TABLE CrossSection (
ObjectID INTEGER NOT NULL,
LeftOverbank_ObjectID INTEGER NULL,
RightOverbank_ObjectID INTEGER NULL,
PRIMARY KEY (ObjectID),
FOREIGN KEY (LeftOverbank_ObjectID) REFERENCES Overbank (ObjectID) ON DELETE CASCADE,
FOREIGN KEY (RightOverbank_ObjectID) REFERENCES Overbank (ObjectID) ON DELETE CASCADE,
);
CREATE INDEX IX_FK_CrossSection_LeftOverbank ON CrossSection (LeftOverbank_ObjectID);
CREATE INDEX IX_FK_CrossSection_RightOverbank ON CrossSection (RightOverbank_ObjectID);
OverBank表
CREATE TABLE Overbank (
ObjectID INTEGER NOT NULL,
Station real NULL,
DisplayLabel text NULL,
Description text NULL,
Name text NULL,
PRIMARY KEY (ObjectID),
);
要启用级联删除,我在OnModelCreating事件中编写了以下内容:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity <CrossSection>()
.ToTable("CrossSection");
modelBuilder.Entity <Overbank>()
.ToTable("Overbank");
modelBuilder.Entity<CrossSection>().HasOptional(xs => xs.LeftOverbank).WithMany().WillCascadeOnDelete(true);
modelBuilder.Entity<CrossSection>().HasOptional(xs => xs.RightOverbank).WithMany().WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
我们可以看到外键约束被颠倒了。此外,当我删除横断面相关的overbank没有得到删除,而当我删除overbank相关的横截面被删除。而我们需要与现在相反的东西。有什么东西很傻。
答案 0 :(得分:1)
每个Overbank属性实际上都是0..1:1的关系。这是“零或一对一”。而不是WithMany()
,请尝试WithRequiredPrincipal()
。