Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework is padding out my text fields although they are not Fixed Length

I am building an MVC3 site using Entity Framework 4 and I'm having a problem with fixed length fields.

When I look at my code during debug it shows that MyEntity.Title="Hello name " with the title padded out to the maximum length of the field.

This is usually a question of having fixed field length in the EDMX file or using a char data type on the underlying database rather than a varchar. In this case neither of those is correct, however it is possible that the problem fields were of fixed length originally. I have manually changed each field in the EDMX ( and the model has been regenerated ) and the fields were never fixed length in the database ( which was the starting point for the application ) so I guess that the need to pad out the fields is being stored somewhere in the Entity Framework configuration and hasn't been updated.

The problem occurs in new records when they are added to the database- when the object is created the Title will be correct, when it is instanciated from the database it is padded.

What do I need to do in order to get rid of the padding, which is really screwing up my string comparisons unless I trim everything?

like image 634
glenatron Avatar asked Apr 03 '12 15:04

glenatron


2 Answers

It turns out that in the .EDMX file the padded files were still listed as nchar. This wasn't visible through the Model Editor, the only way to change it was to right-click on the model in Visual Studio and select "open with..." then use an XML editor. The offending fields looked like this:

<Property Name="MyProperty" Type="nchar" Nullable="false" MaxLength="50" />

Changing the Type to nvarchar and running the template again seemed to clear the problem up.

like image 83
glenatron Avatar answered Oct 08 '22 01:10

glenatron


Existing fields do not get updated in the model when you update it from the database. You either have to delete the entities from the model, or manually change those fields to the new values.

Check the property types in the Model Browser and make sure they are correct.

like image 30
Erik Funkenbusch Avatar answered Oct 08 '22 03:10

Erik Funkenbusch