Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IDENTITY_INSERT with EF4

I am trying to create a record in the db that has a predefined primary key value. I know how to do this with sql, but I was wondering if EF can do this for me? Otherwise, I will have to create a stored proc for the inserts.

like image 714
Paul Knopf Avatar asked Jul 26 '10 03:07

Paul Knopf


People also ask

What does set IDENTITY_INSERT do?

Allows explicit values to be inserted into the identity column of a table.

What is when IDENTITY_INSERT is set to off?

Error 1: Set identity_insert OFF In the first case, we will insert data into the table with the “IDENTITY INSERT” set to “OFF”. So, if the ID is present into the INSERT statement, you will get the error “Cannot insert explicit value for identity column in table 'person' when IDENTITY_INSERT is set to OFF”.


1 Answers

In case you have the StoreGeneratedPattern attribute set to "None" for your entity, the Entity Key value you specify for it will be passed to database.

In case this attribute is set either to "Identity" or to "Computed" there is no way to control what value will be set to this column in DB.

So, if you have an auto-incremented column in your database and the ADO.NET Entity Data Model wizard has set the StoreGeneratedPattern for you, you can manually change this attribute to "None" in the SSDL part of the model using XML Editor, and then enable IDENTITY_INSERT.

You can use the ObjectContext.ExecuteStoreCommand method if you are using EF4 or use the ObjectContext.Connection.StoreConnection property to execute a SQL command SET IDENTITY_INSERT <Your_Table> ON (both in EF1 and EF v4).

like image 183
Devart Avatar answered Dec 28 '22 03:12

Devart