Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework and SQL Server adds blanks in strings?

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 Regards

like image 643
Banshee Avatar asked Dec 18 '10 19:12

Banshee


People also ask

What is include in LINQ to Entity?

LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include() which point towards similar entities must read from the database to get in a single query.

Does EF core create database if not exist?

EnsureCreated will create the database if it doesn't exist and initialize the database schema. If any tables exist (including tables for another DbContext class), the schema won't be initialized. Async versions of these methods are also available.

What is EF in SQL?

Entity Framework Core is a modern object-database mapper for . NET. It supports LINQ queries, change tracking, updates, and schema migrations. EF Core works with many databases, including SQL Database (on-premises and Azure), SQLite, MySQL, PostgreSQL, and Azure Cosmos DB.

How do you add data to EF?

Insert DataUse the DbSet. Add method to add a new entity to a context (instance of DbContext ), which will insert a new record in the database when you call the SaveChanges() method. In the above example, context. Students.


2 Answers

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.

like image 172
TomTom Avatar answered Sep 24 '22 19:09

TomTom


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.

like image 25
James G Avatar answered Sep 23 '22 19:09

James G