2013-09-05 43 views
0

我想爲類(MarriageProfile)中的同一類(Caste)的主鍵(CasteID)放置3個外鍵(三個單獨的字段)。流利的API用於從同一類的多個外鍵

例子:

dbo.MarriageProfile 
MarriageProfileID | CasteID | NaniCasteID | DadiCasteID 
1   | 1 | 3  |  5 

我應該如何添加流利的API爲這一點: 型號是:

Public class MarriageProfile 
{ 
--- 
public int CasteID { get; set; } 
     public virtual Caste Caste { get; set; } 

     public int NaniCasteID { get; set; } 
     public virtual Caste NaniCaste { get; set; } 

     public int DadiCasteID { get; set; } 
     public virtual Caste DadiCaste { get; set; } 
--- 
} 
public class Caste 
    { 
     [Key] 
     [Column(Order = 0)] 
     public int CasteID { get; set; } 

     [Key] 
     [Column(Order = 1)] 
     public string Religion { get; set; } 

     [Key] 
     [Column(Order = 2)] 
     public string CasteCategory { get; set; } 


     public string Title { get; set; } 
     public string Description { get; set; }  

    } 

我試了一下。但生成的遷移文件顯示了許多其他字段。

public partial class castechange : DbMigration 
    { 
     public override void Up() 
     { 
      AddColumn("dbo.UserProfile", "CasteID", c => c.Int()); 
      AddColumn("dbo.UserProfile", "NaniCasteID", c => c.Int()); 
      AddColumn("dbo.UserProfile", "DadiCasteID", c => c.Int()); 
         AddColumn("dbo.UserProfile", "Caste_CasteID", c => c.Int()); 
      AddColumn("dbo.UserProfile", "Caste_Religion", c => c.String(maxLength: 128)); 
      AddColumn("dbo.UserProfile", "Caste_CasteCategory", c => c.String(maxLength: 128)); 
      AddColumn("dbo.UserProfile", "NaniCaste_CasteID", c => c.Int()); 
      AddColumn("dbo.UserProfile", "NaniCaste_Religion", c => c.String(maxLength: 128)); 
      AddColumn("dbo.UserProfile", "NaniCaste_CasteCategory", c => c.String(maxLength: 128)); 
      AddColumn("dbo.UserProfile", "DadiCaste_CasteID", c => c.Int()); 
      AddColumn("dbo.UserProfile", "DadiCaste_Religion", c => c.String(maxLength: 128)); 
      AddColumn("dbo.UserProfile", "DadiCaste_CasteCategory", c => c.String(maxLength: 128)); 
----- 
} 

它應該只包含AddColumn的前三行。 任何幫助!

回答

0

在實體類中使用流利的API或數據註釋。如果使用數據註釋,則將標記標記爲[ForeignKey(「CasteID」)]。

要使用流利的API,你需要通過重寫OnModelCreating比如你的DbContext指定它:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 

    } 

Configuring relationships with Fluent API

你可以省略通過使用常規兩種方法。它要求您的外鍵與您的相關類具有相同的名稱+ Id,例如Caste,CasteId。此關係由EF推斷。

下面是其中更充分地描述了EF約定的鏈接:

Entity Framework Conventions

相關問題