williamsandonz
williamsandonz

Reputation: 16420

How to structure Entityframework DB Contexts

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;
     }
    }
    

Upvotes: 0

Views: 76

Answers (2)

Judo
Judo

Reputation: 5247

  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.

Upvotes: 1

PinnyM
PinnyM

Reputation: 35533

  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.

Upvotes: 1

Related Questions