我正在尝试通过 EF poco 对以下关系进行建模:
Class TableA
{
[Key]
public int TableAId {get;set;}
public Attribute Attribute {get;set;}
}
Class TableB
{
[Key]
public int TableBId {get;set;}
public Attribute Attribute {get;set;}
}
Class Attribute
{
[Key]
public int AttributeId {get;set;}
public string Name{get; set}
}
其中 TableA 和 TableB 都引用了 Attribute。
为此,我插入了以下流畅的映射:
new EntityTypeConfiguration<TableA>().HasRequired(x => x.Attribute);
new EntityTypeConfiguration<TableB>().HasRequired(x => x.Attribute);
一切都很好,我可以使用这种方法添加元素:
var a = new TableA();
var attrA = new Attribute { Name = "Table A Attribute"};
a.Attribute = attrA;
MyDbContext.TableAs.Add(a);
MyDbContext.SaveChanges();
直到我想同时删除 TableA(或 B)和引用的属性。
MyDBContex.TableAs.Remove(a);
MyDBContex.Attributes.Remove(a.Attribute);
这会导致抱怨 FK 的异常。
我必须使用哪些选项来映射和配置此类关系?
我需要插入和删除 TableA 和 TableB 对象并级联删除它们相关的 Attribute 条目。