Entering keys manually with Entity Framework Entering keys manually with Entity Framework asp.net asp.net

Entering keys manually with Entity Framework


Since I prefer attributes, here the alternative for the sake of completeness:

using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;[Key][DatabaseGenerated(DatabaseGeneratedOption.None)]public int Id { get; set; }

Note: This works also in EF Core.


By default Entity Framework assumes that an integer primary key is database generated (equivalent to adding the attribute HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) or calling Property(e => e.EventID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); in the Fluent API.

If you look at the migration that creates the table you should see this:

   CreateTable(                "dbo.Events",                c => new                    {                        EventID = c.Int(nullable: false, identity: true),                        //etc                    })                .PrimaryKey(t => t.EventID );

Then you changed the model using the Fluent API to DatabaseGenerated.None. EF puts this in the migration:

AlterColumn("dbo.Events", "EventID", c => c.Int(nullable: false, identity: false))

And the sql generated is this:

ALTER TABLE [dbo].[Events] ALTER COLUMN [EventID] [int] NOT NULL

Which actually does diddly squat. Dropping the IDENTITY from a column is not trivial. You need to drop and recreate the table or create a new column, then you have to copy the data and fix up foreign keys. So it's not surprising that EF isn't doing that for you.

You need to work out how best to do it for yourself. You could roll back your migrations to 0 and re-scaffold from scratch now that you have specified DatabaseGeneratedOption.None, or you could change the migration manually to drop and recreate the table.

Or you could drop and recreate the column:

DropColumn("Customer", "CustomerId"); AddColumn("Customer", "CustomerId", c => c.Long(nullable: false, identity: false));

EDITOr you could Switch Identity On/Off With A Custom Migration Operation