我不确定我是否正确理解您的模型。让我们讨论一下这些选项。
一会儿,我忽略了这个额外的实体,
ChildContentRelationship并假设该
ChildContent集合是type
ICollection<Content>。
- 选项1:
我认为
ParentContent是 逆属性 的
ChildContent。这意味着如果您有一个
Contentwith
Id=
x,而此Content有一个
ChildContentwith
Id=
y,则ChildContents
ParentContentId必须始终为x。这仅是单个关联,
ParentContent并且
ChildContent是该相同关联的端点。
可以使用数据注释创建此关系的映射…
[InverseProperty("ParentContent")]public virtual ICollection<Content> ChildContent { get; set; }…或使用Fluent API:
modelBuilder.Entity<Content>() .HasOptional(c => c.ParentContent) .WithMany(c => c.ChildContent) .HasForeignKey(c => c.ParentContentId);
我认为这不是您想要的( “ …与…无关”
)。不过,请考虑重命名导航属性。如果有人阅读
Parent...并且
Child...他很可能会假设他们为相同的关系建立了一对导航属性。
- 选项2:
ParentContent不是它的inverse属性,
ChildContent这意味着您实际上有两个独立的关系,并且两个关系的第二个端点都没有在模型类中公开。
的映射
ParentContent如下所示:
modelBuilder.Entity<Content>() .HasOptional(c => c.ParentContent) .WithMany() .HasForeignKey(c => c.ParentContentId);
WithMany()没有参数表示第二个端点不是模型类中的属性,尤其是 不是
ChildContent。
现在,问题仍然存在:
ChildContent属于哪种关系?是一对多关系还是多对多关系?
* 选项2a
如果a
Content引用其他
ChildContents并且不能有第二个
Content引用相同的
ChildContents(a的子代
Content是
唯一的 ,可以这么说),那么您就有一对多的关系。(这类似于订单和订单商品之间的关系:一个订单商品只能属于一个特定的订单。)
的映射
ChildContent如下所示:
modelBuilder.Entity<Content>() .HasMany(c => c.ChildContent) .WithOptional(); // or WithRequired()
您
Content的数据库表中将具有一个附加的外键列,该列属于该关联,但在实体类中没有对应的FK属性。
* 选项2b
如果许多
Content可以引用相同
ChildContent的,则您具有多对多关系。(这类似于用户和角色之间的关系:同一角色中可以有许多用户,并且一个用户可以有许多角色。)
的映射
ChildContent如下所示:
modelBuilder.Entity<Content>() .HasMany(c => c.ChildContent) .WithMany() .Map(x => { x.MapLeftKey("ParentId"); x.MapRightKey("ChildId"); x.ToTable("ChildContentRelationships"); });该映射将
ChildContentRelationships在数据库中创建一个联接表,但此表不需要相应的实体。
* 选项2c
仅在多对多关系除了两个键(
ParentId和
ChildId)之外具有更多属性的情况下(例如,诸如
CreationDateor
RelationshipType或…),您才需要
ChildContentRelationship在模型中引入一个新实体:
public class ChildContentRelationship { [Key, Column(Order = 0)] public int ParentId { get; set; } [Key, Column(Order = 1)] public int ChildId { get; set; } public Content Parent { get; set; } public Content Child { get; set; } public DateTime CreationDate { get; set; } public string RelationshipType { get; set; } }现在您的
Content班级将有
ChildContentRelationships的集合:
public virtual ICollection<ChildContentRelationship> ChildContent { get; set; }您有 两个 一对多的关系:
modelBuilder.Entity<ChildContentRelationship>() .HasRequired(ccr => ccr.Parent) .WithMany(c => c.ChildContent) .HasForeignKey(ccr => ccr.ParentId); modelBuilder.Entity<ChildContentRelationship>() .HasRequired(ccr => ccr.Child) .WithMany() .HasForeignKey(ccr => ccr.ChildId);
我相信您想要选项2a或2b,但是我不确定。



