实体创建外键

时间:2017-04-10 08:44:58

标签: c# foreign-keys entity

我首先尝试使用实体和代码添加外键关系。我有以下简化设置。

public class ChildClass
{
    public int SId { get; set; }
    [ForeignKey("SId")]
    public ParentClass Parent { get; set; }
}

public class ParentClass
{       
    [Key]
    public int SId { get; set; }      
    public ChildClass Child { get; set; }
}

当我尝试添加迁移时,出现以下错误。

Unable to determine the principal end of an association between the types 'ChildClass' and 'ParentClass'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

1 个答案:

答案 0 :(得分:0)

如果您希望SId中的ChildClass属性为PK和FK,则应尝试以下操作:

    public class ChildClass
    {
        [Key, ForeignKey("Parent")]
        public int SId { get; set; }

        public ParentClass Parent { get; set; }
    }

    public class ParentClass
    {
        [Key]
        public int SId { get; set; }

        public ChildClass Child { get; set; }
    }

创建的表格:

家长:

enter image description here

孩子:

enter image description here