I want to use EF Core to map a legacy database. I cannot scaffold as there are hundreds of tables and I am only interested in very few. The situation is: I have a required many-to-one relationship linked by a column name that matches the name of the property that I want to give.
The code (simplified) is:
public class EntityProperty
{
public ControlType ControlType { get; set; }
}
public class ControlType
{
public List<EntityProperty> Properties { get; set; } = new List<EntityProperty>();
}
The problem is, the foreign key column from the EntityProperties
table to the ControlTypes
is also called ControlType
.
So, when I try to map it as:
builder.HasOne(x => x.ControlType)
.WithMany(x => x.Properties)
.IsRequired()
.HasForeignKey("ControlType");
I get the following exception:
InvalidOperationException: The property or navigation ‘ControlType’ cannot be added to the ‘EntityProperty’ type because a property or navigation with the same name already exists on the ‘EntityProperty’ type.’
I guess it’s because I am adding a shadow property when a “physical” property already exists, but I what I really mean to say is to use a different column name to link the two entities.