【问题标题】:Entity Framework Code First - Reference same table实体框架代码优先 - 引用同一张表
【发布时间】:2014-03-17 18:03:10
【问题描述】:

我仍然从 Entity Framework Code First 开始。我希望能够在创建新资源时从列表中选择一个资源。如何使用资源模型引用资源。

public class Resource
{

    public int ResourceId { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string EmailAddress { get; set; }
    [Required]
    public string Password { get; set; }
    public string FullName { get; set; }


    public int TimeManagerId { get; set; }

    public int TravelManagerId { get; set; }

    public int OvertimeManagerId { get; set; }

    public int AbsenceManagerId { get; set; }
    public virtual Resource TimeManager { get; set; }
    public virtual Resource TravelManager { get; set; }
    public virtual Resource OvertimeManager { get; set; }
    public virtual Resource AbsenceManager { get; set; }

}

【问题讨论】:

  • 这看起来不错。这有什么问题?你有错误吗?你的问题到底是什么?
  • 当我生成控制器时,字段不应该是下拉列表吗?我目前只显示 int 文本字段
  • 我不明白这个的逻辑模型是什么。但是你有没有尝试过?
  • @razeth01 这取决于您的要求。您当前的模型说每个 Resource 都有一个 TimeManager、一个 TravelManager 等。如果您需要一个其他资源的列表,那么您需要添加一个资源集合:public virtual ICollection<Resource> MyResources { get; set; }

标签: c# entity-framework asp.net-mvc-4 ef-code-first


【解决方案1】:

我认为你很接近!如果你想按照惯例这样做,你可以将模型中的外键更改为 [navigation property name] [principal primary key property name] 的形式。具体来说,将Id 更改为ResourceId,使其与您引用的表的主表匹配(恰好是它本身)...

public int TimeManagerResourceId { get; set; }
public int TravelManagerResourceId { get; set; }
public int OvertimeManagerResourceId { get; set; }
public int AbsenceManagerResourceId { get; set; }

由于您刚开始使用 EF 代码,我建议您安装 Entity Framework Power Tools。您将能够右键单击包含 DbContext 的 .cs 文件,它会生成一个只读映射图。

用您当前的模型试一试...右键单击图中的实体并查看表映射。您会看到 EF 无法找出您的外键并为您创建了另外 4 个。进行上述更改后,再次生成图表并查看差异。

编辑:关于代码优先约定的文档...http://msdn.microsoft.com/en-us/data/jj679962.aspx

【讨论】:

  • 太棒了!如果您有兴趣,只需使用代码优先约定的参考更新帖子即可。此外,这些通常被称为“自引用”或“分层”实体......如果您需要搜索更多信息,这很方便。
猜你喜欢
  • 2015-06-13
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2014-06-01
  • 2017-07-05
  • 1970-01-01
  • 2017-09-01
  • 2014-05-23
相关资源
最近更新 更多