IDENTITY INSERT and LINQ to SQL

倾然丶 夕夏残阳落幕 提交于 2019-11-27 14:05:40

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.

Set the "Auto Generated" property of the ID Property to "True".

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).

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

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.

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!