繁体   English   中英

实体创建外键

[英]Entity create foreign key

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

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.

如果您希望ChildClass 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; }
    }

创建的表:

家长:

在此处输入图片说明

小孩:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM