[英]EF Optional One-To-One Within Itself
I'm new to Entity Framework and have come across a problem while trying to map my entity. 我是Entity Framework的新手,在尝试映射我的实体时遇到了一个问题。
Basically I have a Location entity which can have an optional parent location. 基本上我有一个Location实体,可以有一个可选的父位置。 So what I'd like on my Location object is to have a collection of child locations along with the parent of the current location.
因此,我希望在Location对象上拥有一组子位置以及当前位置的父级。 Below is my current Location entity:
以下是我当前的位置实体:
public class Location : BaseEntity
{
private ICollection<Location> _childLocations;
public virtual ICollection<Location> ChildLocations
{
get { return _childLocations ?? (_childLocations = new List<Location>()); }
set { _childLocations = value; }
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Location ParentLocation { get; set; }
}
However, when it comes to mapping this, I'm getting pretty lost. 但是,当涉及到映射时,我迷路了。 The below is my attempt so far:
以下是我到目前为止的尝试:
public partial class LocationMap : EntityTypeConfiguration<Location>
{
public LocationMap()
{
this.ToTable("Location");
this.HasKey(l => l.Id);
this.Property(l => l.Name).HasMaxLength(100);
this.HasMany(l => l.ChildLocations)
.WithMany()
.Map(m => m.ToTable("Location"));
this.HasOptional(l => l.ParentLocation)
.WithOptionalDependent()
.Map(m => m.ToTable("Location"));
}
}
Could anyone point me in the right direction? 有人能指出我正确的方向吗?
You want something like: 您想要类似的东西:
this.HasOptional(l => l.ParentLocation)
.WithMany(l => l.ChildLocations)
.Map(m => m.ToTable("Location"));
But not two declarations of the relationship, ie the above replaces both of the below in your example 但是没有两个关系的声明,即上面的示例替换了下面的两个声明
this.HasMany(l => l.ChildLocations)
.WithMany()
.Map(m => m.ToTable("Location"));
this.HasOptional(l => l.ParentLocation)
.WithOptionalDependent()
.Map(m => m.ToTable("Location"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.