dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.8k stars 3.2k forks source link

get names by referance instead of hardcoding #35160

Open hutonahill opened 1 day ago

hutonahill commented 1 day ago

Problem:

I am a newcomer to Entity Framework Core and just getting into using my Entity Framework Core models as the primary source for the schema of my database.

I initially created this model using dotnet ef, pulling the model from an existing database.

When modifying my schema I found that I encounter issues when renaming properties within an IDE. It would not catch the name within quotes of a decorator, for example: [InverseProperty("apartments")]

If I change the property name of apartments that the inverse property is pointing to than I have to go though my model and change every string. this is very annoying.

IDEs have a solution for this. I am using Rider and I can just hit f2 and modify the name of a variable. but when dotnet ef creates a model it hardcodes these values in such a way that it's hard for an IDE to detect that that is supposed to be a reference to a variable name.

Solution:

C# has a solution: nameof. When dotnet ef wants to reference a class name it should be using nameof(structureTypes.apartments) instead of "apartments". This approach is much more data-driven and is easier on IDEs

hutonahill commented 1 day ago

making this conversion in my code base manually, and you probably want to use nameof(Models.StructureTypes.apartments) as StructureTypes is a common name name for objects in the data model

ajcvickers commented 1 day ago

@hutonahill We investigated using nameof before, and even tried it. It did not work out well--see #https://github.com/dotnet/efcore/issues/26588. Scaffolding to use the model builder APIs will generally make the code easier for refactoring tools to understand.

hutonahill commented 1 day ago

Glad I am not the first person to think of this.

Is this the issue you're referring to: https://github.com/dotnet/efcore/issues/26588#issuecomment-1014672272? i don't understand the problem

I scaffold using data annotations