2014-01-23 57 views
0

我正在学习使用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; } 
} 

我想加入到员工的时间对雇员,并加入该项目花费的时间项目到项目ID的时间,我只是不明白EF如何确定关系。我试图使用数据注释来定义关系。我试过使用ForeignKey注释来定义关系,但是这也没有奏效。

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

回答

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

+0

哇,谢谢!这很简单!我会看看链接的文档。感谢您花时间帮助我解决这个问题。 – mack

+0

没问题@mack,很高兴有人帮忙。 – NinjaNye