Linq To Sql and identity_insert

后端 未结 6 1057
星月不相逢
星月不相逢 2021-01-13 04:29

I am trying to do record inserts on a table where the Primary Key is an Identity field.

I have tried calling
mycontext.ExecuteCommand("S

6条回答
  •  [愿得一人]
    2021-01-13 05:10

    What I did is something like this(Nbuider is used to create entities). I create all rows normally except the identity insert row; which is done in the end. This is test data creation hence transaction was not needed.

    using (var entitiesEfContext = new ContextABC())
    {
    
        var platforms = Builder
                                    .CreateListOfSize(4)
                                    .TheFirst(1)
                                    .With(x => x.Description = "Desc1")
                                    .With(x => x.IsDeleted = false)
                                    .TheNext(1)
                                    .With(x => x.Description = "Desc2")
                                    .With(x => x.IsDeleted = false)
                                    .TheNext(1)
                                    .With(x => x.Description = "Desc3")
                                    .With(x => x.IsDeleted = false)
                                    .TheNext(1)
                                    .With(x => x.Description = "Desc4")
                                    .With(x => x.IsDeleted = false)
                                    .Build();
                    foreach (var platform in platforms)
                    {
                        entitiesEfContext.Platform.AddObject(platform);
                    }
                    entitiesEfContext.SaveChanges();
    
                  // the identity insert row (o as id in my case)
    
                   entitiesEfContext.ExecuteStoreCommand("SET IDENTITY_INSERT Platform ON; INSERT INTO [Platform](Platformid,[Description],[IsDeleted],[Created],[Updated]) VALUES (0,'Desc0' ,0 ,getutcdate(),getutcdate());SET IDENTITY_INSERT Platform Off");
    
    
                  }
    

提交回复
热议问题