Define field as auto increment in EF5 migration
I am creating a table using EF migration, for example:
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); How to define an id field for auto_increment? I'm sure it should be possible, but I'm just trying to figure out ...
Thanks.
Well, it seems that setting the "identity: true" property in the field should be enough, but for some reason the field is not defined as IDENTITY (1, 1).
A workaround was found in this post:
And it worked for me like this:
Id = new ColumnModel(PrimitiveTypeKind.Int64) { IsNullable = false, IsIdentity = true }, Now its defining the column as IDENTITY (1, 1)
If you want to automatically generate it in the code, you can skip the annotation in the "Identifier" field and do something like below.
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(); } } For more information, check Entity Key Management.
I got this from the link I showed above the comment.
Hope this helps you.