Entity Framework - Multiple DbContext

Neste capítulo, aprenderemos como migrar alterações para o banco de dados quando houver várias classes DbContext no aplicativo.

  • Multiple DbContext foi introduzido pela primeira vez no Entity Framework 6.0.
  • Várias classes de contexto podem pertencer a um único banco de dados ou a dois bancos de dados diferentes.

Em nosso exemplo, definiremos duas classes de Contexto para o mesmo banco de dados. No código a seguir, existem duas classes DbContext para Aluno e Professor.

public class Student {
   public int ID { get; set; }
   public string LastName { get; set; }
   public string FirstMidName { get; set; }
   public DateTime EnrollmentDate { get; set; }
}

public class MyStudentContext : DbContext {
   public MyStudentContext() : base("UniContextDB") {}
   public virtual DbSet<Student> Students { get; set; }
}

public class Teacher {
   public int ID { get; set; }
   public string LastName { get; set; }
   public string FirstMidName { get; set; }
   public DateTime HireDate { get; set; }
}

public class MyTeacherContext : DbContext {
   public MyTeacherContext() : base("UniContextDB") {}
   public virtual DbSet<Teacher> Teachers { get; set; }
}

Como você pode ver no código acima, existem dois modelos chamados “Aluno” e “Professor”. Cada um está associado a uma classe de contexto correspondente específica, ou seja, Aluno está associado a MyStudentContext e Professor está associado a MyTeacherContext.

Esta é a regra básica para migrar alterações no banco de dados, quando há várias classes de Contexto no mesmo projeto.

  • enable-migrations -ContextTypeName <DbContext-Name-with-Namespaces> MigrationsDirectory: <Migrations-Directory-Name>

  • Add-Migration -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> <Migrations-Name>

  • Update-Database -configuration <DbContext-Migrations-Configuration-Class-withNamespaces> -Verbose

Vamos habilitar a migração para MyStudentContext executando o seguinte comando no Console do gerenciador de pacotes.

PM→ enable-migrations -ContextTypeName:EFCodeFirstDemo.MyStudentContext

Uma vez executado, vamos adicionar o modelo no histórico de migração e para isso, temos que disparar o comando add-migration no mesmo console.

PM→ add-migration -configuration EFCodeFirstDemo.Migrations.Configuration Initial

Vamos agora adicionar alguns dados nas tabelas de alunos e professores no banco de dados.

static void Main(string[] args) {

   using (var context = new MyStudentContext()) {
	
      //// Create and save a new Students
      Console.WriteLine("Adding new students");

      var student = new Student {
         FirstMidName = "Alain", 
         LastName = "Bomer", 
         EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
         //Age = 24
      };

      context.Students.Add(student);

      var student1 = new Student {
         FirstMidName = "Mark",
         LastName = "Upston", 
         EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())
         //Age = 30
      };

      context.Students.Add(student1);
      context.SaveChanges();
		
      // Display all Students from the database
      var students = (from s in context.Students orderby s.FirstMidName
         select s).ToList<Student>();
		
      Console.WriteLine("Retrieve all Students from the database:");

      foreach (var stdnt in students) {
         string name = stdnt.FirstMidName + " " + stdnt.LastName;
         Console.WriteLine("ID: {0}, Name: {1}", stdnt.ID, name);
      }

      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
   }

   using (var context = new MyTeacherContext()) {

      //// Create and save a new Teachers
      Console.WriteLine("Adding new teachers");

      var student = new Teacher {
         FirstMidName = "Alain", 
         LastName = "Bomer", 
         HireDate = DateTime.Parse(DateTime.Today.ToString())
         //Age = 24
      };

      context.Teachers.Add(student);

      var student1 = new Teacher {
         FirstMidName = "Mark", 
         LastName = "Upston", 
         HireDate = DateTime.Parse(DateTime.Today.ToString())
         //Age = 30
      };

      context.Teachers.Add(student1);
      context.SaveChanges();
  
      // Display all Teachers from the database
      var teachers = (from t in context.Teachers orderby t.FirstMidName
         select t).ToList<Teacher>();
		
      Console.WriteLine("Retrieve all teachers from the database:");

      foreach (var teacher in teachers) {
         string name = teacher.FirstMidName + " " + teacher.LastName;
         Console.WriteLine("ID: {0}, Name: {1}", teacher.ID, name);
      }

      Console.WriteLine("Press any key to exit...");
      Console.ReadKey();
   }
}

Quando o código acima for executado, você verá que duas tabelas diferentes são criadas para dois modelos diferentes, conforme mostrado na imagem a seguir.

Recomendamos que você execute o exemplo acima passo a passo para melhor compreensão.