2014-01-23 56 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