1

The answer in this thread is not working for me.

I put this annotation on the PK in my customer class like so.

public class Customer
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)] 
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
}

The database migration creates a configuration showing this one line for the newly added data annotation:

AlterColumn("dbo.Customers", "Id", c => c.Int(nullable: false));

I run the migration and look at the table in SQL Server Management Studio. The customer Id column still has Identity Specification Yes and Is Identity Yes. What am I doing wrong?

Thanks.

Community
  • 1
  • 1
BBauer42
  • 3,549
  • 10
  • 44
  • 81

2 Answers2

2

You are not doing anything wrong. That is a limitation (or maybe it can be considered as a bug) of migrations because SQL server doesn't allow changing IDENTITY on existing columns. It can be set only on new columns. If you change identity value in management studio it will internally execute some complex SQL batch involving temporary table and a lot of data manipulation.

The simplest solution is to delete your database and remove identity definition from your initial migration. Otherwise use SQL profiler to see what SQL management studio is doing when changing column's identity value and use that SQL in your migration instead of AlterColumn.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
1

The EF treats the Id field as a PK, and a PK must have unique values. That what Identity Specification means. Table Column Properties

Setting DatabaseGeneratedOption.None only specifies that the Id will not be generated by the DB Engine, and you will have to provided it (which I don't think is a good idea).

  • Why is it not a good idea? I've mapped over old data and there are about 50,000 customers (for the last 50 yrs at a company). However, the Ids range from 0-999999. There are huge gaps. I don't want to let the DB auto-generate b/c I would then get into customer Ids that are 7 digits when there are 950,000 available 6 digit ids. Thus I start from 0, find next available Id, assign it, and insert new record. Make sense? – BBauer42 Feb 21 '13 at 15:25