0

I am working with a legacy MSSQL database that is using Char instead of Varchar for its string fields. But when I bring the data into my Blazor application using Entity Framework Core, my strings are all padded with spaces which causes all sorts of issues.

Is there a way to have this conversion happen automatically or is there an annotation I can add to my EF Core model class string fields to do this conversion?

Peter H.
  • 11
  • 1
  • 1
    https://romiller.com/2014/10/20/ef6-1workaround-trailing-blanks-issue-in-string-joins/ – Brian Parker Jul 21 '21 at 21:49
  • The database explicitly uses fixed-length strings. The strings **are already padded**, although due to SQL quirks that may not be apparent. If you store `'A'` in a `char(4)` field, it behaves as `'A '`. – Panagiotis Kanavos Jul 22 '21 at 13:56

2 Answers2

1

You could alter that legacy field from CHAR(123) into VARCHAR(123). This will probably not cause any backwards compatibility issue, it will save space for you and you will get rid of the paddings as well.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
1

I found this finally How can I configure Entity Framework to automatically trim values retrieved for specific columns mapped to char(N) fields?

Adding this to my EF core modelbuilder on the Char properties solved the problem:

entity.Property(e => e.Name)
             .HasConversion(
                new ValueConverter<string, string>(v => v.TrimEnd(), v => v.TrimEnd()));
Peter H.
  • 11
  • 1
  • That's a bad and very expensive idea. This means you end up with orphaned temporary strings every time you try to read a string value. Why not switch to `varchar` ? And if the database uses fixed-length strings, why treat them as something different in the client application? – Panagiotis Kanavos Jul 22 '21 at 13:58