sql >> Base de Datos >  >> RDS >> Sqlserver

Linq a Sql e identidad_inserción

Otra opción es envolver todas sus llamadas Linq2Sql en un TransactionScope(). Esto debería forzarlos a todos a ejecutarse en la misma conexión.

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();
       }
       // ...

Aunque, si está tratando de hacer algo como:

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

probablemente se encontrará con otros problemas, especialmente si la columna de identidad tiene el atributo IsDbGenerated establecido en verdadero. El comando SQL generado por Linq2Sql no sabrá incluir la columna de identidad y el valor.