简体   繁体   English

将实体附加到数据上下文

[英]Attaching entities to data contexts

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. 我在global.asax将此代码作为辅助方法。 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. 但是在登录后,这个调用不止一次,并且第二次我最终尝试将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);
}

I believe there are two methods to do this. 我相信有两种方法可以做到这一点。

DataContext.TableName.Contains(Item)

or we use the id field. 或者我们使用id字段。 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)

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. 它认为这是一种更可靠和无状态的策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM