Linq To Sql and identity_insert

后端 未结 6 1044
星月不相逢
星月不相逢 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:19

    Another option is to wrap all your Linq2Sql calls in a TransactionScope(). This should force them all to run in the same connection.

    using System.Transactions; // Be sure to add a reference to System.Transactions.dll to your project.
    
           // ... in a method somewhere ...
           using (System.Transaction.TransactionScope trans = new TransactionScope())
           {
              using(YourDataContext context = new YourDataContext())
              {
                 context.ExecuteCommand("SET IDENTITY_INSERT MyTable ON");
    
                 context.ExecuteCommand("yourInsertCommand");
    
                 context.ExecuteCommand("SET IDENTITY_INSERT MyTable OFF");
              }
              trans.Complete();
           }
           // ...
    

    Although, if you are trying to do something like:

    context.ExecuteCommand("SET IDENTITY_INSERT MyTable ON");
    context.MyTable.InsertOnSubmit(myTableObject)
    context.SubmitChanges()
    context.ExecuteCommand("SET IDENTITY_INSERT MyTable OFF");
    

    you will probably run into other issues, especially if the identity column has the IsDbGenerated attribute set to true. The SQL command generated by Linq2Sql will not know to include the identity column and value.

提交回复
热议问题