2012-09-16 62 views
0

我試圖建立一個一對一的關係,並遇到了一些問題與聲明的屬性爲FK。我已經搜索並閱讀了這裏發佈的一些問題,但沒有解決我的問題。ASP實體框架流利API [ForeignKey的]註釋錯誤

public class User 
{ 
    [Key] 
    public int userId {get;set;} 
    [DisplayName("User Name")] 
    [Required(ErrorMessage="User name required.")] 
    public string username {get;set;} 
    [DisplayName("Password")] 
    [Required(ErrorMessage="Password required.")] 
    [MinLength(6)] 
    public string password {get;set;} 
    [DisplayName("Email")] 
    [Required(ErrorMessage="Email required.")] 
    public string email {get;set;} 

    public virtual List<RoleDetail> roleDetails { get; set; } 
    public virtual Customer customer { get; set; } 
} 

public class Customer 
{ 
    [Key] 
    public int cusomterId { get; set; } 
    [DisplayName("First Name")] 
    [Required(ErrorMessage="First name required.")] 
    public string firstname {get;set;} 
    [DisplayName("Last Name")] 
    [Required(ErrorMessage="Last name required.")] 
    public string lastname {get;set;} 
    [ForeignKey("userId")] 
    public int userId {get;set;} 
} 

我在使用[ForeignKey]註釋時出現此錯誤。而我使用System.ComponentModel.DataAnnotations。此外,[密鑰]工作正常。

The type or namespace name 'ForeignKeyAttribute' could not be 
found (are you missing a using directive or an assembly reference?) 

缺少什麼我在這裏?

+0

這個問題沒有什麼用流利的API做....你正在使用的數據的註解。 –

回答

5

問題在更多Google搜索後解決。事實證明,在[ForeignKey的]註釋是System.ComponentModel.DataAnnotations.Schema

ForeignKey not being recognised in VS2012 RC

+0

很好的發現!你不應該接受我的答案,因爲EF 5顯然是錯誤的。最好接受你自己的答案。我已在回答之上添加了一條評論,以說明這一點。 – Slauma

1

編輯

低於我的答案是正確的EF < 5.0,但它是錯誤的EF> = 5.0。 @ MooCow的答案在這種情況下是正確的。


[KeyAttribute][ForeignKeyAttribute]類都在命名空間System.ComponentModel.DataAnnotations但它們是兩個不同的組件。

[KeyAttribute]位於System.ComponentModel.DataAnnotations.dll程序集,該程序集直接屬於.NET框架。

但是,[ForeignKeyAttribute]位於EntityFramework.dll程序集,它是EntityFramework NuGet程序包的一部分。

在我看來,這隻能意味着你的項目/組件,其中的類位於不具有參考EntityFramework.dll。如果你添加這個參考,它應該工作。

作爲一個方面說明:您試圖定義一個一對一的關係將無法正常工作的方式。您不能使用單獨的外鍵列/屬性。您必須使用主鍵本身作爲外鍵(shared primary key association),如下所示:

public class Customer 
{ 
    [Key] 
    [ForeignKey("user")] 
    public int customerId { get; set; } 
    //... 
    public User user {get;set;} 
} 
+0

我仔細檢查我的NuGet包和EF 5.0RC是存在的。我在類中添加了_System.Data.Entity_,但仍然給出了相同的錯誤。然後,我從我引用刪除_System.Data.Entity.dll_同時保持_EF.dll_但這並沒有解決我的問題。 – MooCow

+0

@MooCow:什麼是「** EF.dll **」?它應該是「** EntityFramework.dll **」。 – Slauma

+0

對不起,我的壞。我簡化了全名。一些更多的Google搜索後問題解決。 – MooCow