Entity Framework: più DbContext
In questo capitolo impareremo come migrare le modifiche nel database quando ci sono più classi DbContext nell'applicazione.
- Più DbContext sono stati introdotti per la prima volta in Entity Framework 6.0.
- Più classi di contesto possono appartenere a un singolo database o due database diversi.
Nel nostro esempio, definiremo due classi Context per lo stesso database. Nel codice seguente sono presenti due classi DbContext per Student e Teacher.
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; }
}
Come puoi vedere nel codice sopra, ci sono due modelli chiamati "Studente" e "Insegnante". Ognuno è associato a una particolare classe di contesto corrispondente, ovvero Student è associato a MyStudentContext e Teacher è associato a MyTeacherContext.
Ecco la regola di base per migrare le modifiche nel database, quando sono presenti più classi Context all'interno dello stesso progetto.
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
Abilitare la migrazione per MyStudentContext eseguendo il comando seguente nella console di Gestione pacchetti.
PM→ enable-migrations -ContextTypeName:EFCodeFirstDemo.MyStudentContext
![](https://post.nghiatu.com/assets/tutorial/entity_framework/images/package_manager_console.jpg)
Una volta eseguito, aggiungeremo il modello nella cronologia della migrazione e per questo, dobbiamo attivare il comando add-migration nella stessa console.
PM→ add-migration -configuration EFCodeFirstDemo.Migrations.Configuration Initial
Aggiungiamo ora alcuni dati nelle tabelle Studenti e Insegnanti nel database.
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 viene eseguito il codice sopra, vedrai che vengono create due diverse tabelle per due diversi modelli, come mostrato nell'immagine seguente.
![](https://post.nghiatu.com/assets/tutorial/entity_framework/images/executed_code.jpg)
Si consiglia di eseguire l'esempio precedente in modo graduale per una migliore comprensione.