3

I run this query:

context.Database.SqlCommand("SET IDENTITY_INSERT [Songs] ON;");

just before I do the .Add() method from a DbSet.

My data still is using the identity value instead of the ID that I'm supplying.

I only want this temporarily (for data migration) and then it should remain auto generated identity in the future.

I'm using SQL Server CE 4 for my database.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ajma
  • 12,106
  • 12
  • 71
  • 90
  • Similar question to http://stackoverflow.com/questions/13086006/how-can-i-force-entity-framework-to-insert-identity-columns – Jez Oct 26 '12 at 13:12

2 Answers2

4

This can be a problem. DbContext handles db connection itself. This works only if inserts are executed on the same connection as turning on identity insert. I think it releases the connection after this command. You can try to use different DbContext's constructor and pass your own opened DbConnection instance and handle its closing by yourselves.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
3

EF can't guess that you've executed an IDENTITY_SET command and change its internal logic accordingly.

If you need to insert specific Id values, use SqlCommand for the inserts too.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154