Ok, so it turns out I'm the idiot here. @KirillBestemyanov in one of his comments said that it was the Equipment
entity that was causing the issue. That's when it all clicked in my head because I was reading, but not understanding the error message. I had it in my head that the Employee
entity was the cause when it wasn't. I was also using the wrong configuration when I was using the WithOptionalPrincipal()
and WithRequiredPrincipal()
methods. I wasn't understanding how they functioned.
The code in the second comment above was in fact correct, but again, I was applying it to the wrong entity which wasn't at fault which is why the error wasn't getting resolved. Understanding where I had gone wrong, I went on a rewrite spree for my entire DbContext
implementation. I now have a much more robust implementation and its Maintainability Index went from 60 to 76, which I'm happy about.
I implemented two base classes which helped me resolve my issues, here's the code in case someone is interested in the future:
Configuration_TEntity class
internal abstract class Configuration<TEntity> :
EntityTypeConfiguration<TEntity>
where TEntity : class, ICreatableEntity, IRemovableEntity, new() {
protected virtual void Configure() {
this.ConfigureCreatableProperties();
this.ConfigureRemovableProperties();
this.ConfigureProperties();
this.ConfigureCreatableRelationships();
this.ConfigureRemovableRelationships();
this.ConfigureRelationships();
}
#region Property Configurations
protected virtual void ConfigureCreatableProperties() {
this.Property(
p =>
p.CreatedDateTime).HasColumnType("datetime2");
}
protected virtual void ConfigureRemovableProperties() {
this.Property(
p =>
p.RemovedDateTime).HasColumnType("datetime2");
}
protected abstract void ConfigureProperties();
#endregion
#region Relationship Configurations
protected abstract void ConfigureCreatableRelationships();
protected virtual void ConfigureRemovableRelationships() {
this.HasOptional(
t =>
t.RemovedBy).WithMany().HasForeignKey(
k =>
k.RemovedById);
}
protected abstract void ConfigureRelationships();
#endregion
}
Configuration_TEntity_TCreatedByKey class
internal class Configuration<TEntity, TCreatedByKey> :
Configuration<TEntity>
where TEntity : class, ICreatableEntity, ICreatableEntity<TCreatedByKey>, IRemovableEntity, new()
where TCreatedByKey : struct {
protected override void ConfigureCreatableRelationships() {
this.HasRequired(
t =>
t.CreatedBy).WithMany().HasForeignKey(
k =>
k.CreatedById);
}
protected override void ConfigureProperties() {
}
protected override void ConfigureRelationships() {
}
}