How to update data using Linq binding method

I have an update method in my data layer, for example:

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 am writing 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 started it, I have this error message: it is impossible to attach an entity that already exists.

How can this be fixed?

+3
source share
3 answers

The easiest way to get around this problem is to use the same DataContext when retrieving the user object and updating it.

In general, a DataContext should be stored for a β€œunit of work,” in other words, you use it to retrieve any object that you want to change, then change its properties, and then simply execute SubmitChanges () on the DataContext. There is no need to bind an object to a DataContext, since it already refers to it.

My VB skills do not exist, but something like that should work (note: a very crude pseudo code is suitable, things like proper placement of a DataContext are 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 Orrel is pretty good at coping with the challenges you experience if you want to go deeper.

+4
source

If the DataContext that you retrieved from the user object was not disconnected or deleted, I don’t think Attach () should be called. What is the life cycle of objUIData?

+2
source

I do not know the answer to your question, and I also stuck to the same problem, but I adopted a simple strategy to prevent these small problems.

Instead of trying to connect / disconnect, select the actual object as soon as possible; this works well in web scripting.

0
source

All Articles