I follow by entity framework example :
http://msdn.microsoft.com/en-us/library/bb399182.aspx
and I have problem with Identity Columns.
Here is part of code of creating database:
CREATE TABLE [dbo].[Person](
[PersonID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[HireDate] [datetime] NULL,
[EnrollmentDate] [datetime] NULL,
CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED
(
[PersonID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
In VS 2010 I build .edmx and at model I see that Person StoreGeneratedPattern is set to Identity.
But when I want to create Person, by :

Why I must put id, if this column is autoincrement?
EDITŁ
I thought that I found the way to resolve my problem by:
var schoolContext = new SchoolEntities();
schoolContext.AddToPeople(new Person() { LastName = "Gates", FirstName = "Bil" });
schoolContext.SaveChanges();
because it added Bill to persons, but…because PersonID is not nullable, and it inserted him with id 0. When I tried add another person the same way of course I get error about primary key 🙂
So still with nothing…
Any ideas ?
I cannot tell you why the EF team chose to do it this way – my only guess would be that the code generation that create the
CreatePersonmethod doesn’t check to see whether or not the ID is an autoincrement and just creates a method that will work in any circumstance – whether the ID is autoincrement or not.If this really bothers you, you can also benefit from the fact that the generated entity class
Personis defined as a partial class, so you can extend it easily. Create a new class file called e.g.PersonEx.csand extend that partial class:Now, you can easily create your
Personentities without specifying an ID, and add them to your data:It’s not a perfect solution – but it should work just fine (at least it does for me).