Click here to Skip to main content
15,881,820 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am inserting multiple records in my table using loop. After insert first record exception Generates.
ERROR:- Cannot add an entity that already exists?

Below is my Code.

Solved-

C#
 PromoCodeForSpecificBook1 obj;
foreach(var i in Model.BookDetail)
                      {
   obj = new PromoCodeForSpecificBook1();
                          obj.BookId = i.ID; //Convert.ToInt32(Model.Id);
                          var P = DB.BookPromoCodes.OrderByDescending(X => X.Id).FirstOrDefault().Id;
                          obj.PromoCodeId =P;
                          DB.PromoCodeForSpecificBook1s.InsertOnSubmit(obj);
                          DB.SubmitChanges();



                        
                      }
Posted
Updated 19-May-15 19:12pm
v3
Comments
Pankit Patel 20-May-15 1:00am    
create new object every time in loop then this error will be removed.
eg. obj = new Object() or whatever.
Naveen Kumar Tiwari 20-May-15 1:10am    
thanks done
Pankit Patel 20-May-15 1:29am    
Enjoy coding :)

1 solution

1.In order to add new records in the database you have to create new objects in your foreach loop.

2.A 2nd problem is the fact that you are reading the same booking promo code for each item and should be read only ones before the foreach.

3.A 3rd optimisation could be to save all changes only ones at the end of the foreach.

The modified source code should be:
C#
var P = DB.BookPromoCodes.OrderByDescending(X => X.Id).FirstOrDefault().Id;
foreach(var i in Model.BookDetail)
                      {
                          PromoCodeForSpecificBook obj = new PromoCodSpecificBook(); //Create your entity!
                          obj.BookId = i.ID;
                          obj.PromoCodeId =P;
                          DB.PromoCodeForSpecificBooks.InsertOnSubmit(obj);
                      }
DB.SubmitChanges(); //Save all changes in a single call!
 
Share this answer
 

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