2013-04-04 86 views
0

我有兩個模型類,我想要做一對一的關係。當我做遷移,我得到一個錯誤:代碼第一對一外鍵

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Uzytkownik_dbo.UserProfile_UserId". The conflict occurred in database "db_wydarzenia", table "dbo.UserProfile", column 'UserId'.

[Table("UserProfile")] 
    public class UserProfile 
    { 
     [Key] 
     [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
     public int UserId { get; set; } 
     public string UserName { get; set; } 
    } 

    [Table("Uzytkownik")] 
    public class Uzytkownik 
    { 
     [Key] 
     public int UzytkownikID { get; set; } 

     public int UserId { get; set; } 

     public string Imie { get; set; } 
     public string Nazwisko { get; set; } 
     public string Telefon { get; set; } 
     public string Email { get; set; } 

     [ForeignKey("UserId")] 
     public UserProfile UserProfile { get; set; } 


    } 

編輯: 問題解決了:) 我從uzytkownik表中刪除所有數據,它的去。

回答

0

如果你想要一對一 - 你不能同時指定主鍵和外鍵。一對一通過主鍵(pk == pk)建模,否則它變成'多樣性'(並且只是典型的一對多)。

要得到什麼,你只想要刪除您的其他PK - 和用戶UserId爲小學和FK ...

[Table("Uzytkownik")] 
public class Uzytkownik 
{ 
    // [Key] public int UzytkownikID { get; set; } 
    [Key] 
    public int UserId { get; set; } 
    [ForeignKey("UserId")] 
    public UserProfile UserProfile { get; set; } 
} 
+0

這不是一個問題。我必須從uzytkownik表中刪除所有數據。感謝您的幫助;) – user1031034 2013-04-04 11:20:45

+0

但您沒有一對一 - 您擁有的是一對多 - 這是唯一真正解決問題 – NSGaga 2013-04-04 11:21:36

+0

是的,您有權利。 – user1031034 2013-04-04 11:23:18