在实体框架代码中,如何对多列使用 KeyAttribute

我正在创建一个 POCO 模型,首先用于实体框架代码 CTP5。我用这个装饰做了一个属性映射到一个 PK 列。但是如何在多个列上定义 PK,特别是如何控制索引中列的顺序?它是否是类中属性顺序的结果?

谢谢!

75464 次浏览

You can specify the column order in the attributes, for instance:

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
}

If you are using the Find method of a DbSet you must take this order for the key parameters into account.

To complete the correct answer submitted by Slauma, you can use the HasKey method to specify an order for composite primary keys as well:

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
});
}
}

If, like me, you prefer to use a configuration file you can do that in this way (based on Manavi's example):

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});
}
}

Obviously you have to add the configuration file to your context:

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


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

Use as a anonymous object:

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