IDENTITY_INSERT during seeding with EntityFramework 6 Code-First

后端 未结 9 724
遥遥无期
遥遥无期 2020-12-05 10:19

I have an entity that has an Auto-identity (int) column. As part of the data-seed I want to use specific identifier values for the \"standard data\" in my syste

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 11:05

    So I might have resolved this one by resorting to generating my own SQL insert statements that include the Id column. It feels like a terrible hack, but it works :-/

    public class Seeder
    {
        public void Seed (DbContext context)
        {
    
            var myThing = new ReferenceThing
            {
                Id = 1,
                Name = "Thing with Id 1"
            };
    
            context.Set.Add(myThing);
    
            context.Database.Connection.Open();
            context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT ReferenceThing ON")
    
            // manually generate SQL & execute
            context.Database.ExecuteSqlCommand("INSERT ReferenceThing (Id, Name) " +
                                               "VALUES (@0, @1)", 
                                               myThing.Id, myThing.Name);
    
            context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT ReferenceThing OFF")
        }
    }
    

提交回复
热议问题