我正在创建一个 POCO 模型以首先与实体框架代码一起使用 CTP5。我正在使用装饰将属性映射到 PK 列。但是如何在不止一个列上定义 PK,具体来说,如何控制索引中列的顺序?它是类中属性顺序的结果吗?
谢谢!
我正在创建一个 POCO 模型以首先与实体框架代码一起使用 CTP5。我正在使用装饰将属性映射到 PK 列。但是如何在不止一个列上定义 PK,具体来说,如何控制索引中列的顺序?它是类中属性顺序的结果吗?
谢谢!
您可以在属性中指定列顺序,例如:
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
}
如果您使用Find
a 的方法,则DbSet
必须考虑此顺序以获取关键参数。
要完成 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
});
}
}
如果像我一样,您更喜欢使用配置文件,您可以这样做(基于 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());
}
}
用作匿名对象:
modelBuilder.Entity<UserExamAttemptQuestion>().ToTable("Users").HasKey(o => new { o.UserId, o.Username });