0

Im using a seperate business logic class to get my Data Object from the database,

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;

    }
}

This works well however when using on my calling page

  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 error i get is

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

Anyone know a way around this, so that i can access all the info in my user object.

4

1 回答 1

2

如果您使用此声明:

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

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

于 2012-07-18T09:57:39.523 回答