2017-04-10 183 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