I am using Entity Framework (Database First) and I am trying to import a bunch of data from an old database into our new one. In some instances it is important for the object IDs to remain the same in the new database as they are in the old one. Normally when you create a new object and call context.SaveChanges() it will automatically assign an identity value to the ID column.
Currently, what is happening is that I will set the new object ID in code, but once I call context.SaveChanges() it is overwritten by the new one assigned by Entity Framework.
I need to be able to set the ID in the new object manually and have it remain once I call context.SaveChanges().
You can set the StoreGeneratedPattern
in the model designer (or in EDMX file) for the key property of your entity to None
. For integer key columns it is Identity
be default which means that Entity Framework does not send the key values to the database because it expects that the database will create the key. If the pattern is None
it sends the value to the database that you supply with the entity.
(For DbContext
(EF >= 4.1) it is called DatabaseGeneratedOption
.)
Of course at the same time you also need to turn off the Identity specification for the key column in the database table.