2017-04-10 98 views
0

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

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. 
+0

尝试把' “父类”',而不是' “SID”' –

+0

是不是注释应该是declarartion以上? –

回答

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