Click here to Skip to main content
15,907,183 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I try to insert multi-records in foreach loop using Entity Framework , first record inserted successfuly , but whet start insert second record an sql exception occured it details say (SqlException: Cannot insert explicit value for identity column in table 'EmployeeVacation' when IDENTITY_INSERT is set to OFF.)

What I have tried:

i try this in sqlserver : SET IDENTITY_INSERT EmployeeVacation ON , but doesn't work
Posted
Updated 1-Jan-18 7:45am
v2
Comments
Patrice T 1-Jan-18 13:05pm    
Try to show your code.
Dave Kreskowiak 1-Jan-18 13:35pm    
Without seeing your code, it's impossible to tell you what you're doing wrong.

1 solution

You're trying to give a field that has a column marked as an IDENTITY column (usually the table ID) an explicit value which isn't allowed, SQL generates the value automatically. You're probably re-using the entity you've added and are trying to re-add it. When you first create the entity it has no ID but is given one when you add it and if you try and re-add it you'll get this problem. Without seeing the code it's impossible to say what the fix is but you're probably doing this;

var e = new MyEntity();
foreach (var i in col)
{
    e.Property = i.Property;
    db.MyTables.Add(e);
}


you need to do this

foreach (var i in col)
{
    var e = new MyEntity();
    e.Property = i.Property;
    db.MyTables.Add(e);
}
 
Share this answer
 
Comments
Ahmed Dabas 2-Jan-18 2:57am    
Thanks bro , it's work :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900