Forum Discussion
Ricardo Peres
May 20, 2024Copper Contributor
EF Core : foreign key column with same name as existing navigation property
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 and besides scaffolding generates names for the navigation prop...
- May 20, 2024
Found a way: define a shadow property with some random name that maps to the actual physical column and use it.
As this:builder.Property("ControlTypeId").HasColumnType("int").HasColumnName("ControlType"); builder.HasOne(x => x.ControlType).WithMany(x => x.Properties).IsRequired().HasForeignKey("ControlTypeId");
This way I never have any "physical" foreign property polluting my model other than the navigation property, and I can give it any name I want,
Ricardo Peres
May 20, 2024Copper Contributor
Found a way: define a shadow property with some random name that maps to the actual physical column and use it.
As this:
builder.Property("ControlTypeId").HasColumnType("int").HasColumnName("ControlType");
builder.HasOne(x => x.ControlType).WithMany(x => x.Properties).IsRequired().HasForeignKey("ControlTypeId");
This way I never have any "physical" foreign property polluting my model other than the navigation property, and I can give it any name I want,