I am working on application where I use EF code first (v4.4) as ORM and SqlServer as database. I also need an option to import data from another database type, which has similar data structure. During the data transfer I need to transfer identity columns with values they have, in order not to break related data.
Assuming this is the sequence of operations:
- fetch the data
- convert it to fit EF model
- add each entity to DbContext
- save changes
the problem is that it will not insert identity values as they were, due to the fact that my primary keys are set as Identity columns.
One of the ways to solve this problem is to use IDENTITY_INSERT command, but it requires to be executed together with insert queries under the same connection cycle. By connection cycle I mean that connection must not be closed during all operations (IDENTITY_INSERT and INSERT INTO).
Problem: ExecuteSqlCommand closes the connection, even if it was explicitly opened prior calling it.
A solution to this problem is to not use EF for this task, but go with ADO.NET SqlCommand. This way we have more control of when the connection will be opened / closed.
Problem: if I change my model, I also need to change the import queries, so I need to maintain database structure on two places.
Any advice how to achieve this with EF? I do not have the slightest idea why did EF team decide to always close the connection after calling ExecuteSqlCommand.