0

I have an entity with a PK defined that is an Identity column in the underlying database. In most cases, I just let SQL Server generate the value for me. However, in certain cases I want to provide a value instead of SQL Server generating one. Am I able to do this with EF 5 (using Code First)?

Randy Minder
  • 47,200
  • 49
  • 204
  • 358
  • The SQL side of it is handled by Set Identity_insert http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx – Kirsten May 07 '13 at 03:10
  • http://stackoverflow.com/questions/15509564/entity-framework-code-first-migrations-set-primary-key-value – Kirsten May 07 '13 at 03:19

1 Answers1

0

If it is SQL Server, then send the commands you need using ExecuteSQLCommand

I created this test as an example

 [Fact]
        private void IdentityInsertOK()
        {
            var sql = "set identity_insert  ConfigSettings on " +
                       "delete from ConfigSettings where id =2 " +
                      "insert into ConfigSettings (Id,Name, value) values (2,'test ','testval')  " +
                      "set identity_insert  ConfigSettings off ";
            using (var Db = SettingsHelper.CreateContext(ConnectionType.Syrius))
            {
                Db.Database.ExecuteSqlCommand(sql);
                Db.SaveChanges();
            }

        }
Kirsten
  • 15,730
  • 41
  • 179
  • 318