ObjectContext实例已被释放,不能再用于需要连接的操作

时间:2012-07-18 09:48:31

标签: c# entity-framework

我使用单独的业务逻辑类从数据库中获取数据对象,

public partial class HelperUsers
{
    public User GetUser(string Username, string Password)
    {

        using (var myEntities = new BusinessLogic.Entities())
        {
            var query = (from u in myEntities.Users
                         join link in myEntities.linkUserPhoneNumbers on u.UserId equals link.UserId
                         join p in myEntities.PhoneNumbers on link.PhoneNumberId equals p.PhoneNumberId
                         where u.UserName == Username && u.Password == Password
                         select u).ToList();



            if (query.Any())
                return (User)query[0];
        }
        return null;

    }
}

但是在我的调用页面

上使用时效果很好
  protected void btnLoad_OnClick(object sender, EventArgs e)
  {
        HelperUsers helper = new HelperUsers();
        var myUser            helper.GetUser("username", "password")
        // This works fine 
        lblUserName.Text =  myUser.Username
        // If i try to read one of the child objects from the join it returns an error
        if (myUser.linkUserPhoneNumbers.Any())
        {
            //do something
        }
  }

我得到的错误是

 The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

任何人都知道解决方法,以便我可以访问用户对象中的所有信息。

1 个答案:

答案 0 :(得分:2)

如果您使用此声明:

using (var myEntities = new BusinessLogic.Entities())

然后你不能使用myUser.linkUserPhoneNumbers.Any(),因为没有加载linkUserPhoneNumbers并且处理了上下文。您需要在查询中包含linkUserPhoneNumbers或保持上下文不受影响。 看这里:http://msdn.microsoft.com/en-us/library/bb896272.aspx