Androidian
Androidian

Reputation: 1075

EF 6 Code First - Integer primary key - Cannot insert the value NULL into column

I'm trying to update the primary key of my table to be an integer autoincrement Id.

This is my entity:

public class Reservation
{
    public int Id { get; set; }
    public ReservationStatus Status { get; set; }
    public string Name { get; set; }
    public string CustomerName { get; set; }

    ...
}

This is my OnModelCreating method:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        ...

        modelBuilder.Entity<Reservation>()
            .HasKey(e => e.Id)
            .Property(e => e.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        ...
    }

This is the generated migration:

public partial class Reservations_AlterKey_Id_AutoIncrement : DbMigration
{
    public override void Up()
    {
        DropPrimaryKey("dbo.Reservations");
        AlterColumn("dbo.Reservations", "Id", c => c.Int(nullable: false, identity: true ));
        AlterColumn("dbo.Reservations", "CustomerTaxCode", c => c.String());
        AddPrimaryKey("dbo.Reservations", "Id");
    }

    public override void Down()
    {
        DropPrimaryKey("dbo.Reservations");
        AlterColumn("dbo.Reservations", "CustomerTaxCode", c => c.String(nullable: false, maxLength: 128));
        AlterColumn("dbo.Reservations", "Id", c => c.Int(nullable: false));
        AddPrimaryKey("dbo.Reservations", new[] { "Id", "DeviceId", "CustomerTaxCode" });
    }
}

When I try to insert a new Reservation (after Update-Database) the following exception is thrown:

Cannot insert the value NULL into column 'Id', table 'xxxxx.dbo.Reservations';

This is what I see in column properties from designer (visual studio 2015):

enter image description here

"Is Identity" is still false.

How can I solve this?

Thanks in advance

Upvotes: 0

Views: 1212

Answers (1)

Martin Lee
Martin Lee

Reputation: 286

You can't add an identity to an existing column in SQL Server.

Adding an identity to an existing column

Suggested fix is to create a new column. The best approach is to add a new identity column, create a migration for it then remove the old column and create a migration for that. This way EF wont just try and rename the old column.

Upvotes: 4

Related Questions