0

I haven't been able to find any answers online for this.

  1. What are the advantages/disadvantages of using Multiple DB Contexts against using a single?

  2. Is the below solution ok for setting related objects, (when saving to DB) (to make it more efficient, because I already have the ID, no need to fetch object)

  3. I've heard its reccommened to use contexts like Using(MyContext c = MyContext) {}, at the moment I'm using the default MVC way, of having the context instantiated in the controller, is this ok?

      Person P = new Person(); 
      P.QuickSetCar(CarID); 
      db.People.Add(P); 
      db.saveChanges();
    

    and

    private void QuickSetCar(int CarID)
    {
      if(this.Car == null) {
        Car C = new Car();
        C.ID = ID;
        this.Car = C;
     }
    }
    

2 Answers 2

1
  1. Using multiple contexts is always a disadvantage unless you have no choice (e.g. your data is dispersed across multiple databases).

  2. Almost, but you can simplify your new car initialization to:

    private void QuickSetCar(int CarID) {
      if(this.Car == null)
        this.Car = new Car(){ ID = CarID };
    }
    
  3. That's fine. Just don't use more than one context for the duration of the web transaction (request/response) and don't keep it around for longer than that either.

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

Comments

1
  1. Multiple contexts are normally only useful for very large models spread over multiple databases. If you are starting a project it is normally best to use a single context.

  2. Your method for using IDs is fine.

  3. Creating contexts within controllers is certainly workable but I would strongly suggest against it. This approach is often shown in demos and for basic scaffolding but in real world applications it is not a great idea. Large amounts of code will often be duplicated by instatiating and querying contexts in each controller. Also have a central repository will allow for much easier caching to improve performance.

2 Comments

Thanks!! Re: #3, my code is DRY, what do you mean by a central repository?
The repo is just a central location for all interactions with the context. It is hard for code to be DRY as the project grows if you are opening and querying contexts in each controller. A good starter for the repository pattern is at blog.appharbor.com/2012/10/31/…

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.