簡體   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