Entity Framework and SQL Server adds blanks in strings?
I have notice that when I read back MS SQL columns of type nchar
NCHAR
is fixed length. If an INSERT
ed or UPDATE
ed value has a smaller length, then spaces are added. Naturally you read back with additional blanks.
This happens when the database is set up in such a way to add blanks.
if you do not want fixed length strings, don't use a fixed length field type. Instead of NCHAR
use NVARCHAR
. The VAR
in there indicates variable length.
TomTom's answer is correct but if you were like me you may still be having an issue.
I changed my table column to varchar(10)
but was still having the spacing issue. I found that my issue was also with my Entity Context definition. Make sure in your .modelBuilder.Entity<your_table>()
does not have the property .IsFixedLength()
on it. I took that out and that fixed my issue.
I have two extension methods that will trim nchar fields within entities. The first will trim a single entity, and the second uses the first to trim a list of entities.
public static T TrimSingleEntity<T>(this T entity) { if (entity == null) return entity; var props = entity.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(prop => prop.PropertyType == typeof(string)) .Where(prop => prop.GetIndexParameters().Length == 0) .Where(prop => prop.CanWrite && prop.CanRead); foreach (var prop in props) { var value = (string)prop.GetValue(entity, null); if (value == null) continue; value = value.Trim(); prop.SetValue(entity, value, null); } return entity; }public static List<T> TrimEntityList<T>(this List<T> entityList) { foreach (var entity in entityList) TrimSingleEntity(entity); return entityList; }