实体框架代码第一关系

时间:2014-01-23 17:22:35

标签: c# entity-framework code-first

我正在使用Code First学习EF,而且我在构建正确的关系时遇到了很多麻烦。

简单员工

public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

一个简单的项目

public class Project
{
    [Key]
    public int ProjectId { get; set; }
    public String ProjectNumber { get; set; }
}

花在项目上的时间

public class Time
{
    [Key]
    public int TimeId { get; set; }
    public int EmployeeID { get; set; }
    public String ProjectID { get; set; }
    public long? TimeSpent { get; set; }

    public virtual Employee Employee { get; set; }
    public virtual Project Project { get; set; }
}

我正在尝试在EmployeeID上加入Employee to Time并在ProjectID上加入Project to Time,我只是不明白EF如何确定关系。我正在尝试使用数据注释来定义关系。我已经尝试使用ForeignKey注释来定义关系,但这两者都没有用。

我将运行,但在Project表上,创建了一个名为Project_ProjectID的新字段,如果我尝试在VS中运行查询,则会收到一条错误消息,指出Time_TimeID列无效(它是...... )。有人可以帮我理解我做错了吗?

1 个答案:

答案 0 :(得分:0)

您不应该需要DataAnnotations,因为conventions在这种情况下适合您

尝试以下

public class Time
{
    [Key]
    public int TimeId { get; set; }
    public int EmployeeID { get; set; }
    public int ProjectID { get; set; }  //<< Changed type from string
    public long? TimeSpent { get; set; }

    public virtual Employee Employee { get; set; }
    public virtual Project Project { get; set; }
}

public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }

    // Set up the other side of the relationship
    public virtual ICollection<Time> Times { get; set; } // << Added
}

public class Project
{
    [Key]
    public int ProjectId { get; set; }
    public String ProjectNumber { get; set; }

    // Set up the other side of the relationship
    public virtual ICollection<Time> Times { get; set; } // << Added
}

这篇文章可能有所帮助 http://msdn.microsoft.com/en-gb/data/jj679962.aspx