c# - EF 可选一对一内部

标签 c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我是 Entity Framework 新手,在尝试映射我的实体时遇到了问题。

基本上我有一个位置实体,它可以有一个可选的父位置。因此,我希望在 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"));

关于c# - EF 可选一对一内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10718415/

相关文章:

c# - 当前上下文中不存在名称 xxx

javascript - Knockout.js:如何对表进行排序?

asp.net-mvc - 当我发布到 Azure 时,ASP MVC4 和 Azure - 捆绑和缩小不再为我工作

c# - 通过套接字读取的最大数据

c# - ASP.NET核心: UsePathBase extracts pathbase from path but MapControllers() does not consider path

c# - 从数据 GridView 当前选定单元格的正下方打开一个弹出窗口

html - Bootstrap 在一行和一列中使用图像渲染文本

c# - stackoverflow 中的标签列表

asp.net-mvc - VXG 媒体播放器在浏览器中出现未知错误

c# - 如何在 ASP.NET CORE 中使用具有依赖注入(inject)的 Action 过滤器?