I have entities with one-to-many relationship. For example Department to Employee. In this example, 'Employee' entity (table) has 'DepartmentID' column in it.
Here are the existing Entities for illustration purpose -
public class Department
{
public int Id {get;set;}
public string Name {get;set;}
public List<Employee> Employees {get;set;}
}
public class Employee
{
public int Id {get;set;}
public string Name {get;set;}
public int DepartmentId {get;set;}
}
Now in the next version, I want to convert this relationship to many-to-many. So, 'DepartmentID' column will go away from Employee table and new intermediate entity (table) 'DepartmentEmployee' will be introduced to manage many-to-many.
Since, the application is already in the production, I want to migrate this automatically using Migration feature in EF Core. For the above example, I have to drop the column 'DepartmentID' from Employee table. But, before dropping it, mapping data should be migrated into the new table (i.e. 'DepartmentEmployee'). That means, Employee ID and corresponding Department ID should be added into the 'DepartmentEmployee' table. Once, it is done, I can drop the 'DepartmentID' column from 'Employee' table.
Here are the new proposed Entities for illustration purpose -
public class Department
{
public int Id {get;set;}
public string Name {get;set;}
public List<DepartmentEmployee> DepartmentEmployees {get;set;}
}
public class Employee
{
public int Id {get;set;}
public string Name {get;set;}
public List<DepartmentEmployee> DepartmentEmployees {get;set;}
}
public DepartmentEmployee
{
public int DepartmentId {get;set;}
public Department Department {get;set;}
public int EmployeeId {get;set;}
public Employee Employee {get;set;}
}
We are using PostgreSQL as database and setting connection string in appsettings.json file. So, we have to supply the connection string to DB Context, which we have configured in DI in Startup. But, since we cannot have constructor with parameter for Migration class, I am not able to inject DB Context into the Migration class.
So, how do I read existing DeparmentID and Employee ID from Employee table, and add them into the new 'DepartmentEmployee' table during migration methods 'Up' and 'Down' for reverse?