Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I temporarily turn off an IDENTITY column in EF Code First?

I'm creating a rewrite of an existing application in EF Code First, but I need to import some of the data from the existing application's database. Here's the definition of my entity class:

public class Business : EntityBase
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AccountNumber { get; set; }

Now, the imported records need to retain their AccountNumber value from the old system. However, new values should use the IDENTITY value generated by the DB.

How do I turn off the IDENTITY while I'm importing old records, then turn it back on for the remainder of the lifetime of the application? Executing this before importing the records has no effect:

context.Database.ExecuteSqlCommand("set identity_insert Businesses on");
like image 420
Josh Kodroff Avatar asked Aug 22 '11 18:08

Josh Kodroff


People also ask

How do I set identity column in Entity Framework?

As you know, EF creates an IDENTITY column in the database for all the id (key) properties of the entity, by default. So, the underlying database generates a value for this column on each insert command, e.g., SQL Server creates an integer IDENTITY column with identity seed and increment to 1.


2 Answers

You can't. Executing a set identity_insert command changes the behavior of SQL Server, but not the behavior of Entity Framework.

You have three choices for importing records:

  • Use raw ADO.NET commands (not entities) or ExecuteSqlCommand.
  • Use a different DbContext, in which you define the keys as non-generated.
  • Use a different technology that's more suited for data conversion, like SSIS
like image 118
Diego Mijelshon Avatar answered Oct 17 '22 23:10

Diego Mijelshon


I recently ran into this same issue. In my case, I was using SQL Server CE. Here's a link to my solution:

Inserting all rows of a DataTable into a SQL Server table, including Id values (scroll down to Edit 2)

This is basically Diego's solution #1 -- raw ADO.NET. It's not a great solution because you will need to customize the queries to account for any differences in databases, but hopefully it will help solve your problem for the moment.

like image 32
devuxer Avatar answered Oct 17 '22 21:10

devuxer