Search code examples
asp.net-mvclinqentity-frameworklinq-to-sqldatacontext

ASP.NET MVC Controller recommendation for LINQ DataContext instantiation place


How should I instantiate the datacontext (entity fw) in a MVC Controller:

  • a) as a property in class
  • b) as a field in class
  • c) as a variable in Action
  • d) as abstract away your DbContext with the Repository pattern

In WebForms I would use c), because b) would maintain the db object state across events, which is usually not what I want.

I actually never used a).


Solution

  • I'd like to start by saying that I 100% agree with @jrummell in that the DbContext should be instantiated. However, if you aren't going to do that, I would use a private readonly field and provide two constructors:

    public MyController() : this(new DbContext()) { }
    
    public MyController(DbContext context)
    {
       this._dbContext = context;
    }
    

    This way you can still inject a DbContext for testing.