In a project that I have to maintain now are all tables mapped like this.
[Table("ab_children")]
public class Children
{
[Key]
[Column("ab_children_pk")]
public string AbChildrenPk { get; set; } = null !;
[Column("ab_address_index_fk")]
public string AbAddressIndexFk { get; set; } = null !;
}
The references to other tables are not mapped as their type but as strings which hold the foreign key value. It gets used everywhere in code. Now I want to use entity references instead wherever I change something.
I tried to add the following code to the mapping.
public AbAddress AbAddress { get; set; } = null !;
But that throws an error at runtime
Invalid Column Name ‘ab_cd_children_pk’
I also tried
[Column("ab_address_index_fk")]
public AbAddress AbAddress { get; set; } = null !;
but I get the same exception.
Is it possible to add a second property that maps to the same table column and how?
1
[Table("ab_children")]
public class Children
{
[Key]
[Column("ab_children_pk")]
public string AbChildrenPk { get; set; } = null !;
[Column("ab_address_index_fk")]
public string AbAddressIndexFk { get; set; } = null !;
[ForeignKey(nameof(AbAddressIndexFk))]
public virtual AbAddress AbAddress { get; set; } = null!;
}
Should be what you’re looking for. Note that the [ForeignKey]
attribute will be the property name of the FK, not the database column name. If you want to use a shadow property (no FK property) then you would use the table column name and EF would create a shadow property that maps directly to that.
EF can mostly configure what you need via attributes and convention, but there will be situations it gets gunked up especially where it cannot rely on convention rules where the development team has their own distinct naming convetion. In these cases I recommend using fluent configuration either with OnModelCreating on the DbContext or via IEntityTypeConfiguration<TEntity>
implementations that are registered with the DbContext model creation.
If you are getting some oddly named missing FKs etc. still, check for any explicit configuration going on with the model creation in the DbContext.
3