【问题标题】:Code first one to one foreign key编码第一个一对一外键
【发布时间】:2013-03-26 05:53:57
【问题描述】:

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

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 表中删除了所有数据,然后就可以了。

【问题讨论】:

    标签: ef-code-first


    【解决方案1】:

    如果您想要一对一 - 您不能同时指定主键和外键。一对一是通过主键(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; }
    }
    

    【讨论】:

    • 这不是问题。我必须从 uzytkownik 表中删除所有数据。感谢您的帮助;)
    • 但你没有一对一 - 你拥有的是一对多 - 这是问题的唯一真正解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    相关资源
    最近更新 更多