How many subclasses of DbContext should I have in relation to my models?

I am learning ASP.NET MVC, and I am having some questions that the training materials that I have read so far have not been studied in a way that covers me. I tried to search, but I had no questions asking about it. However, please forgive me if I skipped the existing ones.

If I have one ASP.NET MVC application that has several models (some of which are related and some are not related to each other), how many subclasses DbContextshould I create if I want to use one connection string and one database worldwide for my application?

  • One context for each model?
  • One context for each group of related models?
  • One context for all models?

If the answer is one of the first two, is there anything I should keep in mind to make sure that only one database is created for the entire application? I ask because when debugging locally in Visual Studio it seems to me that it creates as many databases as there are contexts. That is why I believe that I am using the third option, but I would like to know if this is the right practice or if I make some mistake that will come back and bite me later.

+5
source share
3 answers

@jrummell . Entity Framework DbContext, . " ", @NeilThompson , , , , . , DbContext, , , , :

public class MyContext : DbContext
{
    public MyContext()
        : base("name=DatabaseConnectionStringNameHere")
    {
        Database.SetInitializer(null);
    }
}

, , , .

: 1) ( , ), 2) . , . , , . "" , . - , . .

, , , , . , Cat - , Cat , . , Cat , . , , , . DbSet , , EF DbSet. , , , .

+4

,

SystemUsers Products - DbContext Shop DbContext ().

, .

+5

DbContext. , , DbContext.

, , .

Right, the Entity Framework will create one database by type DbContext.

0
source

All Articles