Entity Framework Non Identity - cannot insert null value in column identifier '

I have a table with the main identifier key, this field is not an identification column. My migration for Entity Framework 6 -

CreateTable( "dbo.Action", c => new { ID = c.Int(nullable: false, identity: false), ActionName = c.String(maxLength: 50), }) .PrimaryKey(t => t.ID); 

All this looks quite frank. Then I have a way to sow some data:

 public static void Seed(this DbSet<Action> entitySet) { MainContext dbCtx = DataRepositoryBase<Action>.GetContext(entitySet) as MainContext; if (dbCtx != null) { entitySet.Add(new Action() { ID = 1, ActionName = "Test" }); } } 

At this moment I get an error

"Cannot insert a NULL value in the column identifier ', table' dbo.Action '; the column does not allow zeros. INSERT fails. Stops"

As you can see, I explicitly provide a value for the ID column. My suspicion is that the Entity Framework expects the identifier to be an Identity column

Entity class is very simple.

 [DataContract] public class Action { [DataMember] public int ID { get; set; } [DataMember] public string ActionName { get; set; } } 
+6
source share
2 answers

Your migration only creates a table in the database, but does not indicate to the Entity Framework that the ID property is not an IDENTITY column. EF selects a property called ID if you do not specify which property to use as the primary key, but you also need to tell EF that it is not an IDENTITY column, do this using the DatabaseGenerated attribute:

 [DataContract] public class Action { [DataMember] [Key] //This isn't technically needed, but I prefer to be explicit. [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ID { get; set; } [DataMember] public string ActionName { get; set; } } 
+6
source

The error is due to the fact that the name of the Id field must be the primary key and identifier.
When EF generates an insert statement, it does not generate a value for this field.

You can fix it using

 [DataContract] public class Action { [DataMember] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int ID { get; set; } [DataMember] public string ActionName { get; set; } } 
+2
source

All Articles