Why multiple DbContext classes?

asp.net-mvc c# entity-framework

Question

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?

1
9
4/26/2013 1:02:06 AM

Accepted Answer

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.

13
4/26/2013 12:59:39 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow