EF 4.1 Code First - one context or several contexts?

Can anyone offer any advice on whether it is best practice to have one context or several contexts?

For example, should I have one context as follows:

public class MyContext : DbContext { public DbSet<Company> Companies { get; set; } public DbSet<Country> Countries { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new CountryConfiguration()); modelBuilder.Configurations.Add(new CompanyConfiguration()); base.OnModelCreating(modelBuilder); } } 

Or is it better for me to create a separate context for companies and countries? So, ConpanyContext and CountryContext, which will both expose the same DbSet property.

It can be only a personal choice, but our database will consist of 100 objects. Therefore, I would like to get this right to begin with.

Many thanks,

Paul.

+6
source share
2 answers

A simple rule of thumb: one schema / domain, one context.

+6
source

If at all possible, try and separate them into meaningful lines.

100 objects in context may seem bad, but think about your alternative, 100 different contexts?

Then you have to do something like

 using(CompanyContext cc = new CompanyContext) { } using (CountryContext cc = new CountryContext) { } 

If you needed to query multiple tables, you would have nested contexts, and that would get ugly. You will start things like

 using(CompanyContext comp = new CompanyContext) { using (CountryContext country = new CountryContext) { } } 

I can’t imagine that the performance will be improved, but I’m sure that the service will be painful.

+2
source

Source: https://habr.com/ru/post/885424/


All Articles