Reputation: 5637
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?
Upvotes: 2
Views: 268
Reputation: 34238
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"));
Upvotes: 4