Im having indirection issues when trying to configure the Fluent API for a property that has a single one-to-one relationship as well as a one-to-many relationship with the same entity. For example:
public class Person
{
public int Id { get; set; }
public int PrimaryNameId { get; set; }
public NameInfo PrimaryName { get; set; } // one-to-one
public IList<NameInfo> Names { get; set; } // one-to-many
}
public class NameInfo
{
public int Id { get; set; }
public int PersonId { get; set; }
public Person Person { get; set; }
public string Name { get; set; }
...
}
I am trying to capture the relationship where a person can have many names but in most cases, I'm only interested in their "PrimaryName". I would prefer to not have a hanging column on the NameInfo table for IsPrimary. That column will end up being NULL/FALSE for >90% of records.
When I tried to manually configure Fluent API for this
**Configuration on Person Entity**
builder.HasOne(c => c.PrimaryName)
.WithOne()
.HasForeignKey<Person>(c => c.PrimaryNameId)
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
builder.HasMany(c => c.Names)
.WithOne(n => n.Person)
.HasForeignKey(n => n.PersonId);
there seems to exist foreign index key constraints that point to each other such that seeding the database fails. In order to add a NameInfo, I need the PersonId - but in order to add a Person, I need an existing NameInfo Id (for the required PrimaryNameId -> Primary Name).