我们正在使用实体框架,我们有一个独特的要求,在尝试了许多可能的选项后,我无法弄清楚我是如何做到的,下面是问题摘要。
我有以下实体
public class SuperParent
{
[Key]
public int SupoerParentId {get;set;}
public virtual ICollection<Parent> Intermediates {get;set;}
}
public class Parent
{
[Key]
public int ParentId {get;set;}
[ForeignKey("SuperParentId")]
public virtual SuperParent Ancestor {get;set;}
public int SuperParentId {get;set;}
public virtual ICollection<Child> Children {get;set;}
}
public class Child
{
[Key]
public int ChildId {get;set;}
[ForeignKey("ParentId")]
public virtual Parent Ancestor {get;set;}
public int ParentId {get;set;}
/// Area of guidance required here..............
/// I just want to some what denormalize table and add SuperParentId also in
/// Child and in Database. As most of time its child we query and its very
/// efficient for us to directly query based on SuperParentId, I want to do
/// something like below:
[ForeignKey("SuperParentId")]
public virtual SuperParent Ancestor {get;set;}
public int SuperParentId SuperAncestorId {get;set;}
}
我们有1:N:N关系,很多时候我们只想绕过Parent和SuperParent直接想要到达Child ...目前多级连接有问题,我们的查询效率不高,我们存储大量数据,每个表有20多列。
问题:
答案 0 :(得分:0)
如果您想要进行此类设计,则默认Child
将从Parent
和SuperParent
进行级联删除,即not allowed in sql。
public int SuperParentId { get; set; } // -> non nullable
如果依赖实体上的外键不可为空,则代码 首先在关系上设置级联删除。 Source
您只需从SuperParent
删除默认的级联删除。
modelBuilder.Entity<Child>()
.HasRequired(c => c.Ancestor)
.WithMany()
.WillCascadeOnDelete(false);
如果您在Child
上收集了SuperParent
,请在致电WithMany
时提及。
public DbSet<Child> Children { get; set; }
使用
更改WithMany
以上
.WithMany(sp => sp.Children)