Linq To Sql和identity_insert

Ron*_*rby 5 .net c# linq sql-server linq-to-sql

我试图在主键是一个Identity字段的表上进行记录插入.

我试过打电话,
mycontext.ExecuteCommand("SET identity_insert myTable ON")
但这没有任何好处.

我得到一个错误的说法IDENTITY_INSERTOFF,当我提交更改.

ON在提交更改之前,如何将其从C#代码中转出来?

编辑

我已经读过这是因为ExecuteCommand的代码在不同的会话中执行.

编辑2

有没有什么办法可以执行一些DDL来从我的C#代码中删除身份规范,进行插入,然后重新打开身份规范?

Joh*_*ers 19

另一种选择是将所有Linq2Sql调用包装在TransactionScope()中.这应该强制它们在同一个连接中运行.

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();
       }
       // ...
Run Code Online (Sandbox Code Playgroud)

虽然,如果你想尝试做类似的事情:

context.ExecuteCommand("SET IDENTITY_INSERT MyTable ON");
context.MyTable.InsertOnSubmit(myTableObject)
context.SubmitChanges()
context.ExecuteCommand("SET IDENTITY_INSERT MyTable OFF");
Run Code Online (Sandbox Code Playgroud)

您可能会遇到其他问题,尤其是在标识列将IsDbGenerated属性设置为true的情况下.Linq2Sql生成的SQL命令不知道包含标识列和值.


mar*_*c_s 4

您需要在单个 T-SQL 代码块中完成所有步骤 - 如果您想打开它,然后执行 LINQ-to-SQL 查询,然后将其关闭,这将非常困难,甚至不可能:(

我看到的唯一真正的解决方案是将整个 SQL 打包成 SQL 语句并执行:

SET IDENTITY_INSERT MyTable ON

(do your update here)

SET IDENTITY_INSERT MyTable OFF
Run Code Online (Sandbox Code Playgroud)

并将其作为单个代码块执行.ExecuteContext()

马克

PS:对于您的编辑#2:不,不幸的是,没有(简单)方法可以从列中删除身份,然后将其重新打开。基本上,您必须创建一个没有 IDENTITY 的新列,复制这些值,删除 IDENTITY 列,然后在完成后向后执行相同的操作 - 抱歉!:-(

PS #2:这确实引出了一个问题:到底需要做什么“身份插入”?定期通过应用程序?当然 - 您可能偶尔会遇到这种需求,但我总是在 SQL Mgmt Studio 中单独执行此操作 - 当然不是在我的应用程序中......(只是好奇您的用例/动机是什么)。