2017-08-05 65 views

回答

3

具有以下属性属性[ForeignKey("Column Name")]。通常,您可以在导航属性上分配外键而不是外键列。

public class Employee { 
    public int Employee Id { get; set; } 
    public int ManagerId { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 

    [ForeignKey("ManagerId")] 
    public virtual Employee Manager { get; set; } 
} 
+0

如果我插入一个员工,将插入一个新的经理行时的经理ID为0是预期的行为?我想我需要一个FK约束。 –

+0

实体框架将识别“ManagerId”列作为主键,并将其定义为SQL Server中的自动增量主键字段。查看[使用MVC 5的实体框架6代码优先入门](https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using- mvc/creation-an-entity-framework-data-model-for-an-asp-net-mvc-application)的完整入门教程,演示了这一点以及更多细节。 –