efcore / EFCore.NamingConventions

Entity Framework Core plugin to apply naming conventions to table and column names (e.g. snake_case)
Apache License 2.0
716 stars 73 forks source link

Is there a way to find in a model builder or somewhere else that a specific convention is used? #220

Closed Shiko1st closed 8 months ago

Shiko1st commented 11 months ago

Sometimes it is needed to write a custom SQL, like constraints or something else. Sometimes such things are inside packages, so the only way to reference a generic model in a custom SQL is to use something like nameof(MyType.MyProp).

Is there a way to find in a model builder or somewhere else that a specific convention is used? Is there a way to get a current converter to use it for making a custom sql (inside a model builder or somewhere else)?

The only way I've found is to use reflection over extensions in options. Am I missing something?

roji commented 11 months ago

Are you trying to get e.g. the database name of a table for an EF entity CLR type? If so, the way to do that is to access the model (e.g. via DbContext.Model), to find the entity (or property, or whatever), and call the metadata getter for that.

For example, if you have a Blog CLR type in your EF model, you can find the name of the database table it's mapped to via context.Model.FindEntityType(typeof(Blog)).GetTableName().

Shiko1st commented 11 months ago

For example, if you have a Blog CLR type in your EF model, you can find the name of the database table it's mapped to via context.Model.FindEntityType(typeof(Blog)).GetTableName().

Thank you for the answer! This is ok when our model is already prepared.

But when we are making a model, I'm not sure this will work. We are defining check constraints while building an entity and we have only access to the type:

public static void AddVeryImportantConstraint<TEntity>(this TableBuilder<TEntity> tableBuilder)
    where TEntity : class, ISomeInterface
{
    tableBuilder.HasCheckConstraint(
            $"CR_{tableBuilder.Name}",
            $"\"{nameof(ISomeInterface.Prop1)}\" < \"{nameof(ISomeInterface.Prop2)}\"");
}
roji commented 11 months ago

If you have a TableBuilder, you can access the model on it via tableBuilder.Metadata.Model.