0

https://stackoverflow.com/a/31856991/5852947

The above answer details how to insert identity column using EF6. You need:

  • using (var transaction = dataContext.Database.BeginTransaction())
  • dataContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] ON");
  • transaction.Commit();
  • change StoreGeneratedPattern property of identity column from Identity to None in model designer

This solution worked for me.

But in the same program once I need to insert a row with identity, and once without identity. It seems it is not possible because you have to set the value of StoreGeneratedPattern before compiling the program.

Istvan Heckl
  • 864
  • 10
  • 22
  • Possible duplicate of [EF7 configuring an identity column](https://stackoverflow.com/questions/29661867/ef7-configuring-an-identity-column) – jpgrassi Feb 25 '18 at 17:05
  • SET IDENTITY INSERT ON is pretty much the same as setting the databaseGeneratedOption to None. use these transactions the statement has been executed to insert the rows needed to be inserted with identity, and other places outside this explicit transaction to insert without Identity insert. – DevilSuichiro Feb 26 '18 at 15:02
  • @jpgrassi The referenced topic is for EF7, which is not official yet – Istvan Heckl Feb 26 '18 at 16:09
  • @DevilSuichiro If only the SET IDENTITY INSERT ON command is used without setting databaseGeneratedOption to None then there will be an exception as detailed in [link](https://stackoverflow.com/a/31856991/5852947) – Istvan Heckl Feb 26 '18 at 16:12
  • @IstvanHeckl true, as EF won't pass the ID parameter, but you told DBMS to expect one. I use two differing constructors for my context explicitly for this - one that sets the PK's to Identity during model creation, and one that sets IDENTITY INSERT before each SaveChanges() and models the PK's to have DatabaseGeneratedOption. None. – DevilSuichiro Feb 27 '18 at 11:24
  • 1
    @DevilSuichiro Are you using DB first approach? If you do then can you please show your solution with a simple example? – Istvan Heckl Feb 28 '18 at 11:32

0 Answers0