DonO
DonO

Reputation: 1070

Store empty string instead of Null in SQL Server database using Entity Framework

There is a third party application table which allows Nulls for a few varchar columns. However, if a null is stored on those columns the application crashes. I cannot make any changes to either the application or the database.

To make matters a little more complicate the models have already been created using a designer and I only have access to a compiled dll that has all the company models.

I have created an ASP.NET MVC page which updates the table however if a column is left blank, a null is inserted in the database.

Is there any way to make sure that if a text box is left blank an empty string is stored in the database instead of null?

Upvotes: 3

Views: 5816

Answers (1)

haydnD
haydnD

Reputation: 2293

Add this to the property in your model:

[DisplayFormat(ConvertEmptyStringToNull = false)]

for example:

[DisplayFormat(ConvertEmptyStringToNull = false)]
public string ValToBeNotNullInDb {get;set;}

https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.convertemptystringtonull(v=vs.110).aspx

Upvotes: 8

Related Questions