Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why multiple DbContext classes?

When I program using LINQ with a .dbml file, there is only one context. But, when I do an MVC site, it seems like I have separate contexts for each entity (which is the way the MVC tutorial showed me how to do it; with "movies" context).

I have:

public class AccountsContext : DbContext
{
    public AccountsContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<Account> Accounts { get; set; }
}

And, I have:

public class ClientsContext : DbContext
{
    public ClientsContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<Client> Clients { get; set; }
}

When I call these, I have to create separate contexts, like:

private AccountsContext db = new AccountsContext();
private ClientsContext clientsContext = new ClientsContext();

... Which is both annoying, and it seems redundant since I know that when I use LINQ, I only have to instantiate a single database object.

Is there a way to use only one contextб and is this recommended?

like image 763
user1477388 Avatar asked Apr 25 '13 23:04

user1477388


1 Answers

There shouldn't be anything stopping you from using one context. The database, and the tooling used to access it, should be completely independent of anything outside of it (business logic, service layer, UI, etc...).

The number of contexts, or how you use them, shouldn't change based on your client technology.

What about MVC leads you to believe that you would need more than one context? And what's stopping you from doing so?

If you think you need to use a context for each entity, because the sample was that way, you don't. Just use one context.

If it helps, this is what a simple context looks like with more than one entity:

public partial class abook_dbEntities : DbContext
{
    public abook_dbEntities()
        : base("name=abook_dbEntities")
    {
    }

    public DbSet<Entity> Entities { get; set; }
    public DbSet<Contact> Contacts { get; set; }
}

If it helps, a typical business flow looks like this:

UI -> Controller -> Business logic -> Data access -> Database

Your data contexts would go in your data layer. Your logic would go in your business logic layer.

like image 92
Bob Horn Avatar answered Oct 21 '22 03:10

Bob Horn