我是 Entity Framework 新手,在尝试映射我的实体时遇到了问题。
基本上我有一个位置实体,它可以有一个可选的父位置。因此,我希望在 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"));
}
}
有人能给我指出正确的方向吗?
最佳答案
你想要这样的东西:
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"));
关于c# - EF 可选一对一内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10718415/