Below is a simplified representation of some entities that I wish to access using an EF Core model. A Company can have an optional one-to-one relationship with its Manager, as well as a one-to-many relationship with its Employees.
public class Company
{
public int Id { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
public virtual Manager Manager { get; set; }
public int? ManagerId { get; set; }
}
public class Employee
{
public int Id { get; set; }
public virtual Company Company { get; set; }
public int CompanyId { get; set; }
}
public class Manager : Employee
{
}
The entities are exposed to EF Core in the usual way:
public DbSet<Company> Companies { get; set; }
public DbSet<Employee> Employees { get; set; }
I have attempted to model their relationships, as follows:
modelBuilder.Entity<Company>()
.HasMany(item => item.Employees)
.WithOne(item => item.Company)
.HasForeignKey(item => item.CompanyId)
.IsRequired(true);
modelBuilder.Entity<Manager>()
.HasOne(item => item.Company)
.WithOne(item => item.Manager)
.HasForeignKey<Company>(item => item.ManagerId)
.IsRequired(false);
However, at runtime, EF Core rejects this configuration with the message "Cannot create a relationship between 'Company.Manager' and 'Employee.Company' because a relationship already exists between 'Company.Employees' and 'Employee.Company'. Navigations can only participate in a single relationship. If you want to override an existing relationship call 'Ignore' on the navigation 'Employee.Company' first in 'OnModelCreating'."
Can anyone suggest how to configure this? Many thanks.