Pregunta

good day for everyone!

Currently working on a project in asp-mvc 2 with Linq to Sql to handle the database.

I see many documentation about Linq to sql in asp mvc, My question is, exactly where I access my data context? What is the place with better performance?

For example, i have MyDBDataContext Class

I can define in my controllers

public class ImaginaryController : Controller
{
  MyDBDataContext context = new MyDBDataContext ();
  
  public ActionResult Index()
    {
        var list = // some code to read context 
        return View(list);
    }        
  }
  .......

Or, in action methods

 public class ImaginaryController : Controller
 {
  
  
  public ActionResult Index()
    {
        MyDBDataContext context = new MyDBDataContext ();
        var list = /* some code to read context */;
        return View(list);
    }


  public ActionResult Create()
    {
        //but create need reference
        MyDBDataContext context = new MyDBDataContext ();
        var list = /* some code to read context */;
        return View(list);
    }
          
  }

Another option would be to create a class to access the data

 public class AccesToBD{
   //maybe
   private MyDBDataContext current;
  
   public static MyDBDataContext GetContext(){
       return current;
   }
 }

Or something more complex like Implementing the Singleton Pattern in C#

What would be the best solution? and why?. Thanks for your answers.

¿Fue útil?

Solución

Ideally you would want to use Dependency Injection for this. In it's basic form you can inject your database context into the controller constructor. That way you won't have to create new instances of the context in all of your controllers/actions etc..

A great example of doing this can be found here:

ASP.NET MVC 4 Dependency Injection - Hands On Lab

It basically helps separate any direct access to your data logic from the controllers/actions - which is super important should you need to change your method of data storage etc..

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top