2011-02-09 17 views
62

我正在創建一個POCO模型,以便與實體框架代碼首先使用CTP5一起使用。我正在使用裝飾來製作屬性映射到PK列。但是我怎樣才能在多列上定義一個PK,具體來說,我如何控制索引中列的順序?這是課堂中教學順序的結果嗎?,如何在多個列上使用KeyAttribute

謝謝!

回答

109

您可以在屬性指定列的順序,例如:

public class MyEntity 
{ 
    [Key, Column(Order=0)] 
    public int MyFirstKeyProperty { get; set; } 

    [Key, Column(Order=1)] 
    public int MySecondKeyProperty { get; set; } 

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

    // other properties 
} 

如果您使用的是DbSetFind方法,你一定要把這個順序的關鍵參數考慮進去。

38

要完成提交Slauma正確的答案,你可以使用HasKey方法爲複合主鍵指定的順序,以及:

public class User 
{   
    public int UserId { get; set; }  
    public string Username { get; set; }   
}   

public class Ctp5Context : DbContext 
{ 
    public DbSet<User> Users { get; set; }   

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<User>().HasKey(u => new 
     { 
      u.UserId, 
      u.Username 
     }); 
    } 
} 
+2

感謝 - 這兩種方法都做工精細。我更喜歡屬性,因爲我從代碼生成我的類,屬性更加簡潔。 – GilShalit 2011-02-10 08:29:17

5

如果像我一樣,你喜歡使用的配置文件你可以做,以這種方式(基於Manavi的例子):

public class User 
{ 
    public int UserId { get; set; } 
    public string Username { get; set; } 
} 

public class UserConfiguration : EntityTypeConfiguration<User> 
{ 
    public UserConfiguration() 
    { 
     ToTable("Users"); 
     HasKey(x => new {x.UserId, x.Username}); 
    } 
} 

很明顯,你必須將配置文件添加到您的上下文:

public class Ctp5Context : DbContext 
{ 
    public DbSet<User> Users { get; set; }   

    protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Configurations.Add(new UserConfiguration()); 
    } 
} 
0

用作匿名對象:

modelBuilder.Entity<UserExamAttemptQuestion>().ToTable("Users").HasKey(o => new { o.UserId, o.Username }); 
相關問題