3

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?

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

5 Comments

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. You think this will work if I create and use a model that overrides the original model? Not sure how to make it work.
yes, you should be able to write a custom model that takes in those objects. a partial class may be perfect for this : msdn.microsoft.com/en-us/library/wa80x488.aspx , stackoverflow.com/questions/20960513/…
With partial I will have to declare all those properties using different names.. Overriding in my opinion is a little bit neater. I will give it a try and let you know how it goes.
Actually given my situation I don't think any of this will work. Your answer was great before I edited the question. If you have a way you know will work please share it. There is no way for me to add those attributes to existing properties that I don't have control over.
Only an opinion: I was always instructed it is better to use NULL in the db versus empty strings as it is an unknown value. Then when querying to fill your form you can use string.IsNullOrEmpty or hasValue for numeric properties to decide how you want to display the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.