99

我正在创建一个 POCO 模型以首先与实体框架代码一起使用 CTP5。我正在使用装饰将属性映射到 PK 列。但是如何在不止一个列上定义 PK,具体来说,如何控制索引中列的顺序?它是类中属性顺序的结果吗?

谢谢!

4

4 回答 4

158

您可以在属性中指定列顺序,例如:

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
}

如果您使用Finda 的方法,则DbSet必须考虑此顺序以获取关键参数。

于 2011-02-09T21:20:09.377 回答
61

要完成 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 
        });
    }
}
于 2011-02-09T21:24:44.817 回答
9

如果像我一样,您更喜欢使用配置文件,您可以这样做(基于 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());
    }
}
于 2013-04-11T15:18:43.453 回答
0

用作匿名对象:

modelBuilder.Entity<UserExamAttemptQuestion>().ToTable("Users").HasKey(o => new { o.UserId, o.Username }); 
于 2018-02-25T15:30:31.777 回答