Automatically Trimming Char Fields in Entity Framework Core

I had an EF Core project recently that was querying a database which only used "char" rather than "varchar" for its string fields, and I wanted to make sure that every property was automatically trimming the value after it was read from the database.

I managed to put this together:

internal static class ModelBuilderExtensions
{
    static readonly ValueConverter<string, string> _trim = new ValueConverter<string, string>(v => v.TrimEnd(), v => v.TrimEnd());

    internal static QueryTypeBuilder<TQuery> TrimStrings<TQuery>(this QueryTypeBuilder<TQuery> query) where TQuery : class
    {
        var properties = query.Metadata.ClrType.GetProperties().Where(p => p.PropertyType == typeof(string));
        foreach (var property in properties)
        {
            query.Property(property.Name).HasConversion(_trim);
        }
        return query;
    }
}

... which lets me do this:

modelBuilder.Query<Item>().ToView("DimItem").TrimStrings();

So whenever I query the context for an Item it will use the DimItem view, and trim all the char properties without me having to map them all by name.

This might come in handy for me one day in the future and by that logic it's worth blogging about. :)

entity-framework
Posted by: Matt Hamilton
Last revised: 29 Mar, 2024 01:18 AM History

Comments

No comments yet. Be the first!

No new comments are allowed on this post.