I am not very sure what design pattern is the most efficent to use when working with ASP.Net MVC and the Entity Framework, so any guidance is much appreciated!
Would you store the context in the Controller-class, or is it better to create a repository?
If you would recommend the repo-design, is it required to initialize the context in each method, like this? Or is it a better way to do this?:
public SomeEntity GetEntity(Guid id) {
using(Context ctx = new Context()) {
// code here...
}
}
I use the Repository pattern. The Context is in the Repository, and lasts as long as the Repository does. The Repository is initialized in Controller.Initialize and disposed in Controller.Dispose. This means one request gets a repository/context until the request is finished, which works very well — requests are short, so the context is disposed quickly. But when an action invokes multiple repository methods, they all use the same context, which makes many things easier.