I'm trying to create two entities as below and add referential constraints to them using Fluent API.
The design it to enforce required Primary Contact with optional Secondary Contact with added requirement that Primary and Secondary may be referring to two different contacts in the ContactInfo entity.
public class Employee
{
public int EmployeeId { get; set; }
public int PrimaryContactId { get; set; }
public int SecondaryContactId { get; set; }
public virtual ContactInfo PrimaryContact { get; set; }
public virtual ContactInfo SecondaryContact { get; set; }
}
public class ContactInfo
{
public int ContactId { get; set; }
public string PhoneNumer { get; set; }
public string Email { get; set; }
}
public class EmployeeConfiguration : EntityTypeConfiguration<Employee>
{
public EmployeeConfiguration ()
{
var employeeEntity = this;
employeeEntity.HasKey(e => e.EmployeeId).ToTable("Employees");
employeeEntity.Property(e => e.EmployeeId).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
employeeEntity.HasRequired(e => e.PrimaryContact).WithMany().HasForeignKey(e => e.PrimaryContactId).WillCascadeOnDelete(true);
employeeEntity.HasRequired(e => e.SecondaryContact ).WithMany().HasForeignKey(e => e.SecondaryContact Id).WillCascadeOnDelete(false);
}
}
It seems to create with required constraints as expected but when I try to add an employee with SecondaryContact set to null, the row created for this new Employee has SecondaryContactId set to same as PrimaryContactId which is not my intention.
I'm not able to understand whether the design is correct in the first place, or the configuration needs to be tweaked to get the right results.