Entity Framework and PostgreSQL: quotation marks issue

Multi tool use
Entity Framework and PostgreSQL: quotation marks issue
The problem I am facing is around SQL queries in pgAdmin 4.
Entity Framework (including its Core edition) capitalizes the names of tables and columns.
Which means your SQL will then look something like
select e."Id", e."Text" from "Entries" e
where e."Text" like '%implicated%'
I was googling the way to prevent Entity Framework from capitalizing names but didn't found out much.
Is there a workaround to avoid wrapping table and column names in quotes?
Thanks in advance!
1 Answer
1
Easy done!
Go to OnModelCreating
method.
OnModelCreating
You need an extension method (the code is shared below)
modelBuilder.NamesToSnakeCase();
Create ModelBuilderExtensions
class and paste the following:
ModelBuilderExtensions
public static void NamesToSnakeCase(this ModelBuilder modelBuilder)
{
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
// Replace table names
entity.Relational().TableName = entity.Relational().TableName.ToSnakeCase();
// Replace column names
foreach (var property in entity.GetProperties())
{
property.Relational().ColumnName = property.Name.ToSnakeCase();
}
foreach (var key in entity.GetKeys())
{
key.Relational().Name = key.Relational().Name.ToSnakeCase();
}
foreach (var key in entity.GetForeignKeys())
{
key.Relational().Name = key.Relational().Name.ToSnakeCase();
}
foreach (var index in entity.GetIndexes())
{
index.Relational().Name = index.Relational().Name.ToSnakeCase();
}
}
}
You can see ToSnakeCase
extension method - here it is in StringExtensions
class:
ToSnakeCase
StringExtensions
public static string ToSnakeCase(this string input)
{
if (string.IsNullOrEmpty(input)) { return input; }
var startUnderscores = Regex.Match(input, @"^_+");
return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
}
Remove the db, recreate migrations, then run dotnet ef database update
- bingo!
dotnet ef database update
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Can you try [Column(“lowerCaseolumnName”)]?
– vivek nuna
Jun 14 at 18:22