简体   繁体   English

实体框架代码优先 - 引用相同的表

[英]Entity Framework Code First - Reference same table

I am still starting with Entity Framework Code First. 我仍然从Entity Framework Code First开始。 I want to be able to select a Resource from list when creating a new resource. 我希望能够在创建新资源时从列表中选择资源。 How do I reference a Resource with a Resource model. 如何使用资源模型引用资源。

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; }

}

I think you're pretty close! 我觉得你很亲密! If you want to do this by convention, you can change the foreign keys in your model to the form of [navigation property name][principal primary key property name]. 如果要按惯例执行此操作,可以将模型中的外键更改为[导航属性名称] [主要主键属性名称]的形式。 Specifically, change Id to ResourceId so it matches the primary of the table you're referencing (which happens to be itself)... 具体来说,将Id更改为ResourceId以便它匹配您正在引用的表的主要内容(恰好是它本身)...

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

Since you're just starting with EF code first, I'd recommend you install the Entity Framework Power Tools. 由于您刚开始使用EF代码,我建议您安装Entity Framework Power Tools。 You'll be able to right-click on the .cs file containing your DbContext, and it'll generate a read-only diagram of the mappings. 您将能够右键单击包含DbContext的.cs文件,它将生成映射的只读图。

Try it out with your current model... right-click on entity in the diagram and view Table Mappings. 尝试使用当前模型...右键单击图中的实体并查看表映射。 You'll see EF wasn't able to figure out your foreign keys and created 4 more for you. 你会看到EF无法找出你的外键并为你创造了4个。 Once you make the changes above, generate the diagram again and see the difference. 完成上述更改后,再次生成图表并查看差异。

Edit: Docs on code first conventions... http://msdn.microsoft.com/en-us/data/jj679962.aspx 编辑:代码第一次约定的文档... http://msdn.microsoft.com/en-us/data/jj679962.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM