An embarrassing situation
I have a situation where I have 2 objects, where 1 is inherited from the other, which should be mapped to two separate tables, but the code usage should be around a base of two objects.
More details
public class Team
{
public virtual int Id { get; set; }
public virtual ICollection<Employee> Members { get; set; }
}
public class Employee
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
public class EmployeeInfo : Employee
{
public virtual int Id { get; set; }
public virtual decimal Amount { get; set; }
}
We have an existing database schema where Employee and EmployeeInfo are separate tables with FK between EmployeeInfo_Id and Employee_Id.
In our system, "managers" will add Employee to the system with a set of personal information (more properties than indicated above), for example, pay and add them to the team. Other areas of the system will use Team or Employee objects for other purposes. We would like the code to be super simple if you can make a comparison.
, , :
public void Foo(string name, decimal pay)
{
var employee = new EmployeeInfo();
employee.Name = name;
employee.Pay = pay;
_team.Employees.Add(employee);
_context.SaveChanges();
}
, EmployeeInfo, EmployeeInfo, Employee Employee TeamEmployees.
, "". .
public class TeamConfiguration : EntityTypeConfiguration<Team>
{
public TeamConfiguration()
{
ToTable("Team");
HasKey(t => t.Id);
HasMany(t => t.Members).WithMany(m => m.Teams)
.Map(m =>
{
m.MapLeftKey("Team_Id");
m.MapRightKey("Employee_Id");
m.ToTable("TeamEmployees");
});
}
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration()
{
ToTable("Employee");
ToTable("EmployeeInfo");
HasKey(t => t.Id);
Property(p => p.Name);
HasMany(m => m.Teams)
.WithMany(t => t.Members)
.Map(m =>
{
m.MapLeftKey("Employee_Id");
m.MapRightKey("Team_Id");
m.ToTable("TeamEmployees");
});
}
}
, -- , FK Employee_Id EmployeeInfo_Id.
, JR.