代码首先一对一的外键

时间:2013-04-04 08:44:55

标签: ef-code-first

我有两个模型类,我希望在这里建立一对一的关系。当我进行迁移时,我收到错误:

  

ALTER TABLE语句与FOREIGN KEY约束冲突   “FK_dbo.Uzytkownik_dbo.UserProfile_UserId”。冲突发生在   数据库“db_wydarzenia”,表“dbo.UserProfile”,列'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表中删除所有数据,然后就可以了。

1 个答案:

答案 0 :(得分: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; }
}