Search code examples
c#sqlentity-frameworkt-sql

How to ignore trailing whitespace?


Say a SQL table contains a column of char(10), and a record contains the value "ABC" in that column. Entity Framework will pass ABC ("ABC" with 7 trailing spaces) when asked for the value.

Is there a way to ask Entity Framework to ignore trailing whitespace when getting the value of a column of type char, essentially having EF treat it like a varchar instead?

A quick look at the methods available in the fluent API has yielded no obvious solutions.Removing entity.Property(e => e.CharColumn).IsFixedLength() does not produce the desired effect of trimming trailing whitespace. Changing the type of the column from char to varchar in the SQL database is not an option in my use case as it could interfere with other programs beyond my control which read this table.


Solution

  • Instead of using an auto property in your entity class, you can create one yourself trimming the values.

    private string _myProp;
    public string MyProp
    {
        get => _myProp?.TrimEnd();
        set => _myProp = value;
    }
    

    Be careful by doing it in the setter. I am not sure about Entity Framework, but EF Core directly assigns the values to the backing field if it finds one, bypassing the setter. Assuming Entity Framework does not bypass the setter:

    private string _myProp;
    public string MyProp
    {
        get => _myProp;
        set => _myProp = value?.TrimEnd();
    }