更新:我应该注意到该Id
属性NavigationPropertyClass
不是数据库生成的。在我的实际模型中,NavigationPropertyClass
它也是层次结构方案的一部分(使用TPH),此处未显示,虽然NavigationPropertyClass
具有DerivedClass1
实例和实例的集合,DerivedClass2
但从基类继承自基类的所有类不一定都是这种情况NavigationPropertyClass
派生。
我的模型的一部分看起来像这样(为简洁起见,省略了其他属性和构造函数):
//Many other classes inherit from this class
//and many of the derived classes are not composed of DerivedClass1 or DerivedClass2
public abstract SomeOtherBaseClass{
public int Id {get; set;} //not database generated, set in the constructor
}
public NavigationPropertyClass: SomeOtherBaseClass{
public DerivedClass1 Derived1 {get; set;}
public virtual ICollection<DerivedClass2> Derived2Collection {get; set;}
}
public abstract class BaseClass{
public int Id {get; set;}
//other properties shared by derived classes
}
public class DerivedClass1: BaseClass{
public NavigationPropertyClass NavigationProperty {get; set;}
//other properties pertinent to DerivedClass1
}
public class DerivedClass2: BaseClass{
public NavigationPropertyClass NavigationProperty {get; set;}
//other properties pertinent to DerivedClass2
}
DerivedClass1
具有带有1-1关系NavigationPropertyClass
,而DerivedClass2
具有带许多-1的关系NavigationPropertyClass
。
我正在尝试在每个派生类中建立标识关系,以便NavigationPropertyClass
从数据库中删除的实例时,的关联实例DerivedClass1
和的任何实例也将从数据库中删除DerivedClass2
。我可以看到的唯一方法是使用TPT继承,但是即使这样,我也无法正常工作。我会发布我的Fluent API配置,但是此时我尝试了很多排列,以至于我不知道要发布哪个。
有什么办法可以做我想做的事吗?如果是这样,Fluent API配置是什么样的?
这是符合您要求的模型。
public abstract class Base
{
public int Id { get; set; }
}
public class Derived1 : Base
{
public int PropDerived1 { get; set; }
public NavigationPropertyClass NavigationProperty { get; set; }
}
public class Derived2 : Base
{
public int PropDerived2 { get; set; }
public int NavigationPropertyClassId { get; set; }
public NavigationPropertyClass NavigationPropertyClass { get; set; }
}
public abstract class SomeOtherBaseClass
{
public int Id { get; set; }
}
public class NavigationPropertyClass : SomeOtherBaseClass
{
public Derived1 Derived1 { get; set; }
public virtual ICollection<Derived2> Derived2s { get; set; }
}
而且,ToTable
在配置模型构建器时,只需要使用TPT继承即可。
public class AppContext : DbContext
{
public DbSet<SomeOtherBaseClass> SomeOtherBaseClasses { get; set; }
public DbSet<Base> Bases { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Derived1>().ToTable("Derived1");
modelBuilder.Entity<Derived2>().ToTable("Derived2");
modelBuilder.Entity<NavigationPropertyClass>().ToTable("NavigationPropertyClass");
modelBuilder.Entity<NavigationPropertyClass>()
.HasRequired(x => x.Derived1)
.WithRequiredDependent(x => x.NavigationProperty);
}
}
并将所有内容保留给EF惯例,除了NavigationPropertyClass::Id
也是FK的部分Derived1
。
结果
简化的NavigationPropertyClass
表约束:
PRIMARY KEY [Id]
FOREIGN KEY([Id]) REFERENCES [dbo].[Derived1] ([Id])
FOREIGN KEY([Id]) REFERENCES [dbo].[SomeOtherBaseClasses] ([Id])
更多的
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句