Dan
Dan

Reputation: 1575

How to fix the error "The ObjectContext instance has been disposed" when we already included the entity?

The answer looks like obvious, but, what I am facing is different. I have 3 tables.. Clients related to Users that is related to Messages. The idea is that I can have a message sent from somebody or nobody, but, always will have a destination;

[Message]
 * UserIdFrom (int) nullable; 
 * UserIdTo (int) not nullable;

Both fields are related to my table

[Users]
 * UserId (int);
 * ClientId (int) not null;

that is related with this another table

[Clients]
 * ClientId (Int);
 * CliName varchar;

My EDMX mapped the tables as following:

[Message]
 * UserIdFrom (int)  
 * UserIdTo (int) 
 + _Navigation properties_ + 
 * UserFrom (0..1) related to [Users] (on Navigation properties) 
 * UserTo   (1..*) related to [Users] (on Navigation properties)

and my Users mapped as:

[Users]
 * UserId (int)
 * ClientId (int)
 + _Navigation properties_ + 
 * Clients related to [Clients]
 * MessageFrom (0..1) related to [Message] (on Navigation properties) 
 * MessageTo   (1..*) related to [Message] (on Navigation properties)

And finally I have the Clients mapped:

[Clients]
 * ClientId (int)
 * ClientName (string)
 + _Navigation properties_ + 
 * Users related to [User]

The problem:

In my controller, I have the ActionResult that return the list of Messages that I (logged in) received from Someone (or nobody). So I have the following code:

return View(db.Users.Where(u => u.UsuEmail.Trim() == User.Identity.Name.Trim()).FirstOrDefault().MessageTo);

In my view, I try to show a text like: Daniel(from) just sent a message to Stackoverflow(to)

For that, I use the following code (to show a list of messages):

@foreach (Messages message in Model)
{
   <p><strong>@message.UserFrom.Clients.ClientName</p>
}

The problem occours when I try to get informations about the Clients inside UserFrom, however, I can get informations about the UserTo;

So, I tried to use the Include function, trying to get information about who sent (MessageFrom). Example:

using (Entities db = new Entities()){    
  return View(db.Users.Include("MessageFrom").Where(u => u.UsuEmail.Trim() == User.Identity.Name.Trim()).FirstOrDefault().MessageTo);
}

or

using (Entities db = new Entities()){    
  return View(db.Users.Include("MessageFrom.Clients").Where(u => u.UsuEmail.Trim() == User.Identity.Name.Trim()).FirstOrDefault().MessageTo);
}

The most interesting thing is that I can get information about the addressee, but I can't get information from the sender.

I know how to use Include function (because I am using it in another situation), but, this time I don't know what I need to do.

Upvotes: 1

Views: 78

Answers (0)

Related Questions