This blog post is archived. I consider it outdated and not very useful anymore but since there are many who still visit these pages I've decided to keep them up.
Entity Framework primary key issues
Entity Framework Primary key but not auto-increment
I ran into an interesting problem today with regards to an Entity Framework model having a Primary Key that was not auto-increment.
As a test I created the following model:
public class Person() {
[Key] public int ID {get;set;}
public string Name {get;set;}
}
I created a table in sql2008 with the exact same structure and I executed the following code. The primary key is an integer but is not auto-increment
var owner = new Person() { ID = 1, Name = "Owner" };
db.People.Add(Person);
db.SaveChanges();
Using sql profiler I was able to see the sql being generated by Entity Framework
exec sp_executesql N'insert [dbo].[People]([Name])
values (@0)
select [ID]
from [dbo].[People]
where @@ROWCOUNT > 0 and [ID] = scope_identity()',N'@0 varchar(50),@0='Owner'
As you can see there’s no ID being passed to the query
What I ended up doing was having to set the following code in the OnModelCreating
method
modelBuilder.Entity<Person>()
.HasKey(p => p.ID)
.Property(p => p.ID)
.StoreGeneratedPattern = StoreGeneratedPattern.Identity;
Hope this helps anyone else out there.