Tell Entity Framework to use the name "Children" instead of "InverseParent" when generating entities

c# ef-database-first entity-framework-core generated-code

Question

We are using Entity Framework Core for a large project with database-first design. We use the "scaffold" command to generate entities from the database. In other words, we are doing something like this in the NuGet package manager:

Scaffold-DbContext "Server=foo;Database=bar;" Microsoft.EntityFrameworkCore.SqlServer -Context Fubar -Force

In general, this does a wonderful job of generating entity classes for us.

But there is one annoyance. Microsoft has something called the InverseProperty Attribute for denoting inverse relationships. So if you have an SQL table of type Node, with a ParentId pointing back to the same table, the generated code looks like this:

public class Node {
    public Guid ParentId { get; set; }
    public Node Parent { get; set; }
    public ICollection<Node> InverseParent { get; set; } // the name is annoying
} 

I understand why Microsoft needed a convention here. They don't know what the property names are going to be, and they need a way to invert them when generating the relevant navigation properties.

But in practice for us, the property that is getting inverted is Parent. And time after time, therefore, we see InverseParent, InverseParentFoo, and the like. It would be considerably better if the generated names were Children, ChildFoos, and so on.

We regenerate our entities pretty often. If the choice is between introducing a tool and living with the silly name, we would likely choose to live with the silly name.

Any suggestions for changing the generated name?

1
2
6/29/2018 5:00:19 PM

Popular Answer

Taking @GraemeMiller's advice, here's my powershell script. It also runs scaffolding, so you don't have to run multiple commands.

$connectionString = "your connection string"
$efProject= "your ef project name, also used a folder path for this script"

dotnet ef dbcontext scaffold $connectionString Microsoft.EntityFrameworkCore.SqlServer --context "MyContext" --force --project $efProject --data-annotations

foreach ($file in Get-ChildItem -Path $efProject *.cs) {
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "InverseParent", "Children" } |
    Set-Content $file.PSPath
}
1
6/9/2019 2:59:52 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow