alim
alim

Reputation: 747

ASP.NET MVC Entity Framework Relationship binding

I'm using Entity Framework 5.0 for my MVC4 project. There's a problem with it. When i give a db model to any view, controller send model with no relationship

example;

I have User class and with relation departments

when i use it in controller

using(context)
{
  var user = context.Find(id);
  string department = user.Department.Name;
} 

its working when call in context. but when i do that

using(context)
{
  var user = context.Find(id);
  return View(user);
} 

and call in view like

Model.Department.Name 

i got error.

Here is my answer but its not good

using(context)
{
  var user = context.Find(id);
  string department = user.Department.Name;
  return View(user);
} 

when i try to user Model.Department.Name in view i got no error i must do that for every relation when i use class as model. there is have better solution for this problem ? i want use all relationship in View without call these in controller.

I hope you can understand me, sorry my english.

Upvotes: 4

Views: 594

Answers (3)

JeppePepp
JeppePepp

Reputation: 589

What are u trying to accomplish? List a view for a user with one or many departments?

Upvotes: 1

Steve Gordon
Steve Gordon

Reputation: 17

The reason for this is that you haven't "loaded" the Department in your original code. As your context is wrapped in a using statement it's being disposed of before the view is created and therefore your user object lacks the data you want.

In your second code example you have specifically called into the related Department object and therefore it now exists within the User object.

You need to eager load the Department in your original line using something like

context.User.Include(c => c.Department).Find(id);

Now your user object should have this available in the view.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039200

On your DbContext you could use the .Include method to eagerly load the relations you need:

context.Users.Include(u => u.Department).FirstOrDefault(u => u.Id == id);

or if you are using an older version of entity Framework the generic version of this method might not be available:

context.Users.Include("Department").FirstOrDefault(u => u.Id == id);

Upvotes: 1

Related Questions