开发者

Entity Framework and SQL Server adds blanks in strings?

开发者 https://www.devze.com 2023-01-31 01:36 出处:网络
I am building a ASP.NET MVC application with Entity Framework and SQL Server. I have noticed that when I read back SQL Server columns of type nchar or text there will be added blanks at the end of th

I am building a ASP.NET MVC application with Entity Framework and SQL Server.

I have noticed that when I read back SQL Server columns of type nchar or text there will be added blanks at the end of the string. To fix this I have to run Trim() on the string?

How can I solve this?

Best Regar开发者_开发知识库ds


I have notice that when I read back MS SQL columns of type nchar

NCHAR is fixed length. If an INSERTed or UPDATEed 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;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号