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)
        return query;

... which lets me do this:


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. :)

Posted by: Matt Hamilton
Last revised: 15 Aug, 2019 05:30 AM History


No comments yet. Be the first!

No new comments are allowed on this post.