On occasion, I need to insert a specific ID as the primary key of an entity I'm adding to my data. In classic MS SQL, you can do this by calling SET IDENTITY_INSERT tablename ON
before calling the INSERT INTO
statement. I cannot seem to figure out a way to do the same using EF 4.1 Code First.
Dim specificIdRecord As New Record() With {
.RecordID = 25,
'other settings here
}
myDbContext.Records.Add(specificIdRecord)
myDbContext.SaveChanges()
specificIdRecord.RecordID '<== this does not always equal 25!
There's also no error being thrown to tell me it's ignoring my RecordID and automatically generating one.
NOTE: I do not want to modify my model or modify my context as this is only intended for occasional insert operations. Also, I did see a possible solution using ExecuteStoreCommand
to manually set the IDENTITY_INSERT
before and after the insert runs, but that will require three transactions AFAIK, I want EF to wrap this all up into one.