0
votes

I have a database first design. I want to have default values for my model so that a user can just leave an editor textbox blank for one of my nullable fields. EF doesn't seem to want to just throw null into the database, so I was hoping I could set default values to null for my nullable attributes.

Ie I want to insert null into my database for an attribute if the textbox is left blank when submitted.

I've read you can add a contructor to a partial class to do what I want. So you would basically have:

public partial class MyClass{
    public MyClass()
    {
        field1 = null; //this would be the default value for field1
    }
}

The only problem is the autogenerated partial class for the model I'm working on already has a constructor, so I can't add a constructor to a different (permanent) partial class. I don't want to update the autogenerated partial class because it will just be overwritten when I update my edmx from the database.

1

1 Answers

0
votes

The default value of the string should already be null, so I think you are taking the wrong path.

The problem is a textbox will always be passed with a form post, even if it is blank, which will result in an empty string in your controller rather than a null value, even if you find a way to explicitly set your string to null in your initial class.

Instead, check the value of the string in your controller after the form is posted back, and if it is empty, set it to null.

if (String.IsNullOrEmpty(formModel.MyString)) formModel.MyString = null;

Either that, or create a default model binder to check the value of the field during model binding, and not set it if it is empty.