【问题标题】:in entity framework code first, how to use KeyAttribute on multiple columns首先在实体框架代码中,如何在多列上使用 KeyAttribute
【发布时间】:2011-06-24 10:17:37
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: entity-framework code-first entity-framework-ctp5


    【解决方案1】:

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

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

    【讨论】:

    • InvalidOperationException:实体类型“XXX”具有使用数据注释定义的复合主键。要设置复合主键,请使用 fluent API。
    【解决方案2】:

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

    【讨论】:

    • 谢谢 - 两种方法都可以正常工作。我更喜欢属性,因为我是从代码生成我的类,而且属性更加简洁。
    • 我个人还将 Propety(x...).HasColumnOrder(0...n) 添加到每个键控属性中。这是好事,坏事,冷漠吗?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      用作匿名对象:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-29
        • 2012-05-03
        • 2011-07-29
        • 1970-01-01
        • 1970-01-01
        • 2011-05-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多