繁体   English   中英

EF自身内部一对一可选

[英]EF Optional One-To-One Within Itself

我是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"));
    }
}

有人能指出我正确的方向吗?

您想要类似的东西:

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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM