2

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

谁能指出我正确的方向?

4

1 回答 1

4

你想要这样的东西:

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"));
于 2012-05-23T10:53:25.447 回答