Make ALL Strings From Entity Framework Database Uppercase

.net-core asp.net-core entity-framework-core

Question

This is a hypothetical or "is this possible?" question.

I'm using Entity Framework in ASP.Net Core 2.2 MVC. Is there a way to make ALL strings coming from the database to uppercase? I don't want to store them as uppercase, I just want them to be uppercase when I retrieve them.

Preferably, I'd like it to be just 1 place in my code as opposed to writing a bunch of "getters" on model properties.

1
1
4/17/2019 7:46:41 PM

Accepted Answer

"There is currently no way to specify in one place that every property of a given type must use the same value converter. This feature will be considered for a future release." - Microsoft, Entity framework core docs.

Read the same doc. for applying conversions to individual fields (in OnModelCreating ).

1
4/17/2019 8:31:04 PM

Popular Answer

For a workaround, you could try to configure the HasConversion by looping Models and properties.

Try code like:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
    public DbSet<Product> Products { get; set; }
    public DbSet<Tag> Tags { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        var converter = new ValueConverter<string, string>(
                v => v,
                v => v.ToUpper());
        foreach (var entityType in builder.Model.GetEntityTypes())
        {
            foreach (var property in entityType.GetProperties())
            {
                if (property.ClrType == typeof(string))
                {
                    builder.Entity(entityType.Name)
                           .Property(property.Name)
                           .HasConversion(converter);
                }
            }
        }
    }
}


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