Reputation: 4169
I have a serious problem, i have an unique key on field in db, I use Oracle(Devart Provider).
First time i preform an Insert -> (_objectSet.Add(entity))
via my repository it's ok,
BTW: I use Code Only model and CTP5.
Then if i want to insert it again it's fires an error that i have a "unique key constraint" and it's also alright.
After that no matter what do i do it's always throws me the same error!
What is that and how to fix it?
Thank you in advance.
Upvotes: 1
Views: 554
Reputation: 4169
The answer is simpler then i thought, i just have to Dettach the entity from Context, After i receive an exception of duplicate entities or any exception on it's holds in the context, the right way is to Dettach the entity and that's it.
I've got this answer from Andrey in Devart.
Upvotes: 0
Reputation: 1174
Are you trying to do an .Add(entity) with the same entity? Then you will get that error. If you want to change something in that entity just do the changes like "entity.rowname = value" and then save without trying to do an .Add(entity) and it should work just fine.
How you usually do it is something like this.
Create new row in database:
Entity entity = new Entity();
entity.value = value;
db.Entity.AddObject(entity);
db.SaveChanges();
Retrieve and edit a row:
var entity = db.Entity.SingleOrDefault(e => e.value == value);
entity.value = newValue;
db.SaveChanges();
You can also do something like this without problem
Entity entity = new Entity(); //creating a new Entity
entity.value = 1; //Setting a value on the new Entity
db.Entity.AddObject(entity); //Adding the Entity to the context
db.SaveChanges(); //Saving the record to the database
entity = db.Entity.SingleOrDefault(e => e.value == 2); //retrieving another, already added record
entity.value = 5; //Changing the value on the retrieved record
db.SaveChanges(); //Saving the change to the database
entity = new Entity(); //creating yet another new Entity
entity.value = 8; //setting the value on the second new Entity
db.Entity.AddObject(entity); //adding the Entity to the context
db.SaveChanges(); //Saving the second new Entity to the database
You can NOT do like this
var entity = db.Entity.SingleOrDefault(e => e.value == value);
entity.value = newValue;
db.Entity.AddObject(entity); //WRONG!
db.SaveChanges();
Or this
Entity entity = new Entity();
entity.value = value;
db.Entity.AddObject(entity);
db.SaveChanges();
entity.value = newValue;
db.Entity.AddObject(entity); //WRONG!
db.SaveChanges();
In this case it will try to insert the already tracked entity as a new row with the same key and it will complain that there is already a previous row with the same key by throwing an "unique key constraint" error.
Upvotes: 1