Attaching entities to data contexts
-
09-06-2019 - |
Question
In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it?
A little context if it helps...
I have this code in my global.asax
as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the Member
object in the same unit of work where it was created.
private void CheckCurrentUser()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
AppHelper.CurrentMember = null;
return;
}
IUserService userService = new UserService();
if (AppHelper.CurrentMember != null)
userService.AttachExisting(AppHelper.CurrentMember);
else
AppHelper.CurrentMember = userService.GetMember(
HttpContext.Current.User.Identity.Name,
AppHelper.CurrentLocation);
}
Solution
I believe there are two methods to do this.
DataContext.TableName.Contains(Item)
or we use the id field. If the item is inserted in the Database, then it will be assigned a row.
if(Item.id == 0)
DataContext.Insert(Item)
else
DataContext.Update(Item)
OTHER TIPS
Rather than attaching to a new data context why not just requery the object in the new datacontext? It believe it is a more reliable and stateless strategy.