C# 将实体附加到数据上下文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attaching entities to data contexts
提问by Rob
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?
在 LINQ to SQL 中,是否可以在尝试附加实体之前检查它是否已经是数据上下文的一部分?
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.
我有这个代码global.asax
作为辅助方法。通常,在请求之间,这不是问题。但是在登录后,这被多次调用,第二次我最终尝试将Member
对象附加到创建它的同一工作单元中。
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);
}
采纳答案by Tilendor
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.
或者我们使用 id 字段。如果该项目被插入到数据库中,那么它将被分配一行。
if(Item.id == 0)
DataContext.Insert(Item)
else
DataContext.Update(Item)
回答by liammclennan
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.
为什么不在新数据上下文中重新查询对象,而不是附加到新的数据上下文?它认为这是一种更可靠和无状态的策略。