首页 文章

首先在实体框架代码中,如何在多个列上使用KeyAttribute

提问于
浏览
78

我正在创建一个POCO模型,用于实体框架代码,首先是CTP5 . 我正在使用装饰来创建PK列的属性映射 . 但是如何在多个列上定义PK,具体来说,如何控制索引中列的顺序?这是 class 中属性顺序的结果吗?

谢谢!

4 回答

  • 0

    如果像我一样,你更喜欢使用配置文件,你可以这样做(基于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());
        }
    }
    
  • 128

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

    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 方法,则必须考虑此关键参数的顺序 .

  • 46

    要完成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 
            });
        }
    }
    
  • 5

    用作匿名对象:

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

相关问题