2

私は Entity Framework を初めて使用し、エンティティをマップしようとしているときに問題に遭遇しました。

基本的に、オプションの親の場所を持つことができる Location エンティティがあります。したがって、私が 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"));

ただし、関係の2つの宣言はありません。つまり、上記は、例の以下の両方を置き換えます。

    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 に答える