1

I'm endeavouring to create a site with many models. Should I have individual contexts, or should I just have one? I've already put all my Dbsets in the umbrella context I made, just so that Add-Migration and Update-Database actually works. (cause it can only handle 1 context).

I've noticed each strongly typed controller has a instance of its associated model context. Now I'm wondering if I should just have one open context (my umbrella superclass context) permanetly open for a page life cycle. It seems way too inefficient to keep creating new instances of a context and disposing them (inside local methods) all the time. What is the recommended way of going about this?

1 Answer 1

1

It is better to have one context track many entities. The same context can then track all entities and it will be useful when using a join query and updating entities that have foreign key relationship. Also you can use fluent API to configure the entities in the DBContext method "OnModelCreating". If the context doesn't have them all then configure entity relationships becomes difficult. Grouping entities under different context will eventually affect code maintenance. I like fluent API way to configure entities which keeps the model clean and future proof.

The DBContext has Dispose method that you can override. We can make better use of it. Besides DBContext creates a database context from where is it called which is absolutely fine. That's what we want, isn't it? A incoming request comes as a thread which creates a DBContext( a database context) and then query the database, fetches model and then populates view which is then returned to user.

The important thing is using the "using" statement for DBContext which will instantly dispose the context after scope is out of the using brace. If you do this then you have no trouble with context living through the request life cycle.

using (MyDbContext dbCtx = new MyDbContext()) { //fetch the model } //here the context is disposed. 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.