HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Using separate DBContext classes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
classesdbcontextusingseparate

Problem

I know that the DBContext represents a session (Unit-Of-Work and Repository) with the database, however I an unsure as to when I should have a different DBContext. Currently, I have a separate DBContext for each table with a single DBSet for each DBContext.

Something like this (Blogs and Posts are in the same database):

public class BlogContext : DbContext
{
    public DbSet Blogs { get; set; }        
}

public class PostContext : DbContext
{
    public DbSet Posts { get; set; }
}


I'm not sure why I had a separate DBContext. I think that it is a sample I followed that was like this. However, I recently found that I get an exception when trying to do queries involving both contexts:


The specified LINQ expression contains references to queries that are
associated with different contexts.

So, it seems that the obvious solution is for a single DBContext and multiple DBSets:

public class BlogContext : DbContext
{
    public DbSet Blogs { get; set; }        
    public DbSet Posts { get; set; }
}


Is there any guideline for when to use different DBContexts and the pros and cons of each approach?

Solution

As you have already mentioned, DbContext is a UoW, and DbSet is a repository -- there is no need to reimplement those patterns, unless you're into ridiculously useless complexity.

Entity Framework wraps all pending changes in a transaction for you already, so each DbContext in an application contains DbSets that are somehow related. Blogs and Posts are definitely related, so they belong under the same context.

If your app had a blog module and a completely distinct chat module, you could use separate contexts, as your app would never be using both in the same controller.

I have an app with dozens of absolutely unrelated modules; either I defined a single context with 650 entity types (and only used a fraction of it every time), or I broke it down into much smaller and sanely manageable modules... I went for the second option. (the app is an ERP extension)

Context

StackExchange Code Review Q#30856, answer score: 15

Revisions (0)

No revisions yet.