Linq To Sql and identity_insert

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

    You need to do all the steps in a single T-SQL code block - which is going to be really hard if not impossible if you want to turn it on, then execute your LINQ-to-SQL query, and then turn it back off :(

    The only real solution I see is to package up the entire SQL into a SQL statement and execute that:

    SET IDENTITY_INSERT MyTable ON
    
    (do your update here)
    
    SET IDENTITY_INSERT MyTable OFF
    

    and execute that as a single code block using .ExecuteContext()

    Marc

    PS: for your EDIT#2 : no, unfortunately, there's no (easy) way to remove the identity from a column, and turn it back on. Basicall you'd have to create a new column without the IDENTITY, copy the values over, drop the IDENTITY column and then do the same backwards when you're done - sorry! :-(

    PS #2: this really begs the question: what on earth to do need to do an "identity insert" for? On a regular basis, from an app? Granted - you might run into this need once in a while, but I'd always do this separately, in SQL Mgmt Studio - certainly not in my app..... (just curious what your use case / motivation is).

提交回复
热议问题