Linq to SQL: Why am I getting IDENTITY_INSERT errors?

前端 未结 7 707
长发绾君心
长发绾君心 2020-12-17 02:49

I\'m using Linq to SQL. I have a DataContext against which I am .SubmitChanges()\'ing. There is an error inserting the identity field:

Cannot insert explicit value for         


        
7条回答
  •  旧时难觅i
    2020-12-17 03:33

    If you are supplying the value of the IDENTITY column, you must add

    SET IDENTITY_INSERT ON
    

    before your SQL Statements, and

    SET IDENTITY_INSERT OFF 
    

    after to turn it off. That goes for ANY raw SQL. If you used LINQ to create an object like:

    var customer = new LinqContext.Customer;
    customer.FirstName = "Bob";
    customer.LastName = "Smith";
    
    LinqContent.Customer.Add(customer);
    LinqContext.SubmitChanges();
    

    I believe that will work, forgive me if I have classes wrong. You get the basic idea.

    Edit: Oops.. Sorry, didn't read the entire question, I take it back, tired and fatigued from work...

提交回复
热议问题