开发者

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

开发者 https://www.devze.com 2023-03-03 10:32 出处:网络
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):

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 con开发者_Go百科text 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


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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消