ASP.NET MVC Entity Framework Linkage Bindings

I am using Entity Framework 5.0 for my MVC4 project. There is a problem with that. When I give a db model for any view, the dispatcher sends the model without relation

Example

I have a user class and relationship departments

when i use it in the controller

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

works when called in context. but when i do it

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

and call it like

 Model.Department.Name 

I got an error.

Here is my answer, but its bad

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

when I try to use Model.Department.Name in the view, I did not get an error, I have to do this for each relationship when I use the class as a model. is there a better solution to this problem? I want to use all the relationships in the view without invoking them in the controller.

I hope you can understand me, sorry, my English.

+4
source share
3 answers

In your DbContext, you can use the .Include method to actively load the relationships you need:

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

or if you are using an earlier version of the Framework entity, the general version of this method may not be available:

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

The reason for this is that you did not “download” the Department into your source code. Since your context is wrapped in a using statement, it is deleted before creating the view, and therefore your user object does not have the necessary data.

In your second code example, you specifically called the associated object of the object, and therefore now it exists in the User object.

You need to look forward to loading the Department in the source line using something like

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

Your custom object should now have this available in the view.

+1
source

What are you trying to accomplish? Specify a user opinion with one or more departments?

+1
source

All Articles