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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

This is what I ended up doing. I had to use SqlCeCommand. I wanted to keep my code agnostic of the database, but I guess I can't.
Well, SET IDENTITY_INSERT isn't particularly db-agnostic anyway :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.