實體框架 - 多個 DbContext



在本章中,我們將學習如何在應用程式中存在多個 DbContext 類時將更改遷移到資料庫。

  • 多個 DbContext 最初是在 Entity Framework 6.0 中引入的。
  • 多個上下文類可能屬於單個數據庫或兩個不同的資料庫。

在我們的示例中,我們將為同一個資料庫定義兩個上下文類。在下面的程式碼中,有兩個用於學生和教師的 DbContext 類。

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; }
}

如您在上面的程式碼中看到的,有兩個名為“Student”和“Teacher”的模型。每個模型都與一個特定的對應上下文類相關聯,即 Student 與 MyStudentContext 相關聯,Teacher 與 MyTeacherContext 相關聯。

以下是在同一個專案中有多個上下文類時,遷移資料庫更改的基本規則。

  • 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

讓我們透過在程式包管理器控制檯中執行以下命令來為 MyStudentContext 啟用遷移。

PM→ enable-migrations -ContextTypeName:EFCodeFirstDemo.MyStudentContext
Package Manager Console

執行後,我們將模型新增到遷移歷史記錄中,為此,我們必須在同一控制檯中觸發 add-migration 命令。

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

現在讓我們在資料庫中的 Students 和 Teachers 表中新增一些資料。

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();
   }
}

執行上述程式碼後,您將看到為兩個不同的模型建立了兩個不同的表,如下面的影像所示。

Executed Code

我們建議您逐步執行上述示例,以便更好地理解。

廣告