我是Entity Framework的新手,在尝试映射我的实体时遇到了问题。
基本上我有一个Location实体,它可以有一个可选的父位置。所以我在Location对象上想要的是拥有一个子位置的集合以及当前位置的父级。以下是我当前的位置实体:
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; }
}
然而,当涉及到映射时,我变得非常迷失。以下是我到目前为止的尝试:
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"));
}
}
有人能指出我正确的方向吗?
答案 0 :(得分:4)
你想要这样的东西:
this.HasOptional(l => l.ParentLocation)
.WithMany(l => l.ChildLocations)
.Map(m => m.ToTable("Location"));
但不是关系的两个声明,即上面替换了你的例子中的以下两个
this.HasMany(l => l.ChildLocations)
.WithMany()
.Map(m => m.ToTable("Location"));
this.HasOptional(l => l.ParentLocation)
.WithOptionalDependent()
.Map(m => m.ToTable("Location"));