How do you mix the concepts of ASP.NET MVC and entityframework in a elegant and robust way when it comes to retrieving stuff from the database and visualizing it via the controller and view?
The example below will throw Dispose exceptions because the View will be displayed after the using statement is closed.
// code in controller
using (var usersDb = new UsersDb(new WebSecurityWrapper()))
{
var user = usersDb.GetUser(User.Identity.Name);
return View(user);
}
// code in usersDb model -- GetUser method
public User GetUser(string name)
{
var id = _webSecurity.GetUserId(name);
var user = Users.FirstOrDefault(usr => usr.Id == id);
return user;
}
Pretty obvious, but the only alternative I can think of is "cloning" the user object so that the View can display it independently. That doesn't feel right.
So what's the appropriate way of doing this?