C#/PLINQO - Detach and re-attach the same entity to the same context fail

599 Views Asked by At

I am using PLINQO for my LINQ-TO-SQL data layer.

I have the following piece of code (not real code, just to re-produce the error I am getting):

var context = new MyDataContext();
var user = context.User.GetByKey("username");
user.Detach();
context.User.Attach(user);

Executing the last line of code results with InvalidOperationException with the following error message: "Cannot attach an entity that already exists."

I thought that the Detach method should detach the entity from the context and it seems that it just removing the link from the entity to the context but the context still "remembers" the entity.

How can I detach the entity completely so I will not get the error ?

Thanks, Koby

2

There are 2 best solutions below

2
Koby Mizrahy On BEST ANSWER

I came into conclusion that my desing was incorrect and did not take into account the restrictions on linqtosql, I did changes to the code so situation like that will not happen and if it will an exception will be thrown.

0
asolovyov On

Try to use ObjectStateManager with attached entity:

var context = new MyDataContext();
var user = context.User.GetByKey("username");
// change field values
...
user.AnyUserField = "123";
...
context.AcceptAllChanges();
context.ObjectStateManager.ChangeObjectState(user, EntityState.Added); // or use EntityState.Modified if it already exist anywhere
context.SaveChanges();