I have a update method in my data layer such this:
public clacc datalayerSec_User
private objUIData as new UIData
Public Function Update(ByVal objUser As SEC_USER) As Boolean
Try
objUIData.SEC_USERs.Attach(objUser)
objUIData.Refresh(RefreshMode.KeepCurrentValues, objUser)
objUIData.SubmitChanges(ConflictMode.ContinueOnConflict)
Return True
Catch ex As Exception
Throw ex
End Try
End Function
end class
And I write this code to update my data:
Dim tmpUser As New UI_Class.BAL.Security.cls_SEC_USER
Dim tblUser = tmpUser.GetAll.SingleOrDefault(Function(x) x.DS_OPENID = pOpenID)
tblUser.DT_LAST_LOGIN = DateTime.Now
tmpUser.Update(tblUser)
When I run it, I have this error message: Cannot attach an entity that already exists.
How can it be fixed?
The easiest way to get around this issue is to use the same DataContext when retrieving the user object and updating.
In general, a DataContext should be kept alive for a "unit of work", in other words, you use it to retrieve whatever object you want to change, then change its properties, and then just do SubmitChanges() on the DataContext. No need to reattach the entity to the DataContext, since it already has a reference to it.
My VB skills are none existing, but something like this should work (note: very crude pseudo code coming up, things like properly disposing of the DataContext is recommended):
class cls_SEC_USER
{
private _UIData = new UIData();
public User SingleOrDefault(int x)
{
return _UIData.Users.SingleOrDefault(y => y.UserId == x);
}
public void Update(User u)
{
_UIData.SubmitChanges();
}
}
// ..........
cls_SEC_USER tmpUser = new cls_SEC_USER();
User u = tmpUser.SingleOrDefault(4);
if(u != null)
{
u.DT_LAST_LOGIN = DateTime.Now;
tmpUser.Update(u);
}
Brian Orrell has a pretty good run-down of the issues that you are experiencing, if you want to dig in deeper.
If the DataContext that you retrieved the user object from hasn't been disconnected or disposed, I don't think need to call Attach(). What is the lifecycle of objUIData?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With