【问题标题】:Define a field as autoincrement in EF5 migration在 EF5 迁移中将字段定义为自动增量
【发布时间】:2012-12-25 19:29:59
【问题描述】:

我正在使用 EF 迁移创建一个表,例如:

this.CreateTable("Message",
            c => new
            {
                Id = c.Long(nullable: false, identity: true, defaultValue: 0),
                Subject = c.String(nullable: false, maxLength: 64),
                Body = c.String(nullable: false, isMaxLength: true)
            })
            .PrimaryKey(c => c.Id)
            .Index(c => c.Id, unique: true);

如何将 Id 字段定义为 auto_increment?我很确定这一定是可能的,但我只是在努力寻找......

谢谢。

【问题讨论】:

  • 除了使用注解之外,没有别的方法吗?我可以看到的另一个选项只是使用原始 sql 来创建具有标识的列,但是......感觉应该有一种方法可以通过代码来完成。

标签: asp.net-mvc entity-framework


【解决方案1】:

好的,似乎在字段中设置属性“identity:true”就足够了,但由于某种原因,该字段未定义为 IDENTITY(1, 1)。

在这篇文章中找到了解决方法:

http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/33db16ac-e166-455f-a47b-1e5fe0557979/

它对我来说是这样的:

Id = new ColumnModel(PrimitiveTypeKind.Int64) { IsNullable = false, IsIdentity = true },

现在将列定义为 IDENTITY(1, 1)

【讨论】:

    【解决方案2】:

    如果您确实想在代码中自动生成它,您可以跳过 Id 字段上的注释并执行以下操作。

    public abstract class AbstractContext : DbContext {
    
          /// <summary>
          /// Custom processing when saving entities in changetracker
          /// </summary>
          /// <returns></returns>
          public override int SaveChanges()
          {
              // recommended to explicitly set New Guid for appropriate entities
              foreach (var entry in ChangeTracker.Entries<ModelBase>().Where(e => e.State == EntityState.Added) ) {
    
                  // only generate if property isn't identity...
                  Type t = entry.Entity.GetType();
                  var info = t.GetProperty("Id").GetCustomAttributes(
                      typeof(DatabaseGeneratedAttribute), true).Cast<DatabaseGeneratedAttribute>().Single();
    
                  if (info.DatabaseGeneratedOption != DatabaseGeneratedOption.Identity) {
                      entry.Entity.Id = Guid.NewGuid(); // now we make it
                  }
              }
              return base.SaveChanges();
          }
    
        }
    

    更多信息请查看Working with Entity Keys

    我是从上面评论中显示的链接中得到的。

    希望对你有帮助。

    【讨论】:

    • 对不起,我没有解释自己,我的意思是应该有一种方法可以通过使用迁移代码将列设置为 IDENTITY(1,1)。无论如何,我找到了一个可行的解决方案!请在下面查看我自己的答案。
    猜你喜欢
    • 2016-10-08
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2022-10-25
    • 2015-03-06
    相关资源
    最近更新 更多