I have a SQL Server database. This database has a table called Item. Item has a property called \"ID\". ID is the primary key on my table. This primary key is an int with a
Set the "Auto Generated" property of the ID Property to "True".
The ID will be zero until you call context.SubmitChanges();. Step through the code and look at the value after SubmitChanges has been invoked. Remember, the DB is actually assigning the ID (assuming that it's a auto-increment key).
Take a look at this:
Working with Entity Keys
The simplest way is: 1. open dbml 2. Select class for inserting 3. Select column with primary-key 4. check Auto Generated Property in properties window (it should be set to True)
You must define in your mapping that id is generated in the database. The way to do this depends on the type of mapping you are using. if you are using code attributes make sure that you specify IsDbGenerated
in the ColumnAttribute
for the Id
property (or in XML mapping). if you are using dbml file make sure that Auto Generated Value is set to true.
It sounds simply as though your model is unaware of the fact that it is an identity; the ID
column should be marked as db-generated (Auto Generated Value
in the UI, or IsDbGenerated
in the xml), and probably as the primary key. Then it will not attempt to insert it, and will update the value correctly after it is written.
Check your ID
property inside the Item
class to ensure that it have attributes like this:
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert,
DbType="INT NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
Look at the IsDbGenerated=true
, it is the important guy here.
Maybe you created the DatabaseContext
using the designer before adjusting the IDENTITY
on the Sql Server, so just regenerate this class (by deleting the table in the designer and dropping it from the Server Explorer again).