Reputation: 55
I am using Linq for Insert,Delete and update the database in my code.
While inserting data using InsertOnSubmit, I Am getting the cannot add an entity that already exists
Exception.
Please have a look my code
private static void AddNewPriceSettings(PRICE_SETTING priceSettingsInfo)
{
PRICE_SETTING priceSetting = new PRICE_SETTING();
priceSetting = priceSettingsInfo;
DataContext.CommonUsers.PRICE_SETTINGs.InsertOnSubmit(priceSettingsInfo);
DataContext.CommonUsers.SubmitChanges();
}
Upvotes: 2
Views: 6191
Reputation:
just set the properties for the new priceSetting.
private static void AddNewPriceSettings(PRICE_SETTING priceSettingsInfo)
{
PRICE_SETTING priceSetting = new PRICE_SETTING();
//
priceSetting.Prop1 = priceSettingsInfo.Prop1;
priceSetting.Prop2 = priceSettingsInfo.Prop2;
priceSetting.Prop3 = priceSettingsInfo.Prop3;
// ...
DataContext.CommonUsers.PRICE_SETTINGs.InsertOnSubmit(priceSetting );
DataContext.CommonUsers.SubmitChanges();
}
Upvotes: 2
Reputation: 8417
cannot add an entity that already exists
The problem is clearly stated by the error message. You already have a row in your database that contains the same entity as the one you are trying to insert.
How does SQL decide if two items are "the same"? It uses a key column, which usually is an integer id.
So that leads me to ask you - how does your column definitions look for the affected table? And where are you getting the PRICE_SETTING
that is passed into the method?
The problem could also be that you are trying to perform an update on an already existing object - in that case you need to use different methods. Please share more info regarding the context.
Upvotes: 0
Reputation: 151738
If you call AddNewPriceSettings()
using an existing PRICE_SETTING
object, you're indeed trying to add it again. The second line in your method does that. The new PRICE_SETTING();
you create on the first line is then not referenced to anymore and will be GC'ed without trying to insert it.
If you want to create a copy, you'll have to clone the priceSettingsInfo
into the priceSetting
variable (you can use various techniques for that) prior to inserting and submitting it.
Upvotes: 0