简体   繁体   中英

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.

Basically I have a Location entity which can have an optional parent 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. 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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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