Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Update Data With Linq By Attach Method

Tags:

asp.net

linq

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?

like image 577
mavera Avatar asked Dec 12 '25 22:12

mavera


2 Answers

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.

like image 115
Egil Hansen Avatar answered Dec 15 '25 18:12

Egil Hansen


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?

like image 34
Zachary Yates Avatar answered Dec 15 '25 19:12

Zachary Yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!