开发者

Looking for recommendations to migrate data into an Entity Framework Code First generated Database

开发者 https://www.devze.com 2023-02-10 05:51 出处:网络
I\'m trying to figure out how to migrate data from an SQL server database to an entity framework database that\'s generated with code first.

I'm trying to figure out how to migrate data from an SQL server database to an entity framework database that's generated with code first.

The source database doesn't match the schema exactly so I have some code that will do the migration. What I'm trying to figure out is the best way to move the data over and preserve the IDs. I have zero attributes applied to my model. I'm just using the modelnameID convention for the primary key property.

S开发者_JAVA百科hould I turn off identity generation, migrate data, then turn it back on? What happens to the next value? Should I turn off identity permanently and manage the IDs myself? Any other suggestions?

Edit: I'm using SQL CE 4 for my database.


Here's some code to do it. You won't be able to use DBCC, but you can just alter your column:

var connection = new SqlCeConnection(context.Database.Connection.ConnectionString);
connection.Open();
new SqlCeCommand("SET IDENTITY_INSERT [Songs] ON;", connection).ExecuteNonQuery();
SqlCeCommand command = new SqlCeCommand("INSERT INTO table values", connection);
new SqlCeCommand("SET IDENTITY_INSERT [Songs] OFF;", connection).ExecuteNonQuery();

new SqlCeCommand("ALTER TABLE Songs ALTER COLUMN SongID IDENTITY(100,1)", connection).ExecuteNonQuery();


Turn off identity generation.

Transfer data.

Turn identity generation back on.

Use reseed to set the value of the next id, see: http://msdn.microsoft.com/en-us/library/ms176057.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号