0

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.

1 Answer 1

1

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..

Sign up to request clarification or add additional context in comments.

3 Comments

not know whether to asp mvc 2, should follow the same structure?
It certainly can. Some of the code may differ slightly, though the pattern can 100% be used in MVC 2.
Dependency Injection is a design pattern - meaning it doesn't actually have anything to do with asp.net directly. It's a way of doing things to make life easier. There are libraries available, such as Unity and Ninject that allow you to use this pattern in your particular project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.