0

During save I have an empty TextBox on my page because it is not required and the user decided not to fill it out.

From what I remember in VB.NET when I do the following it will save to the database as NULL, but in C# it seems to be saving as an empty string. I am using Entity Framework 6 DB First

myobject.Phone = PhoneTextBox.Text

Do I really have to do the following for every single non required textbox during save?

    if (string.IsNullOrEmpty(txtPhone.Text))
    {
        myobject.Phone = null;
    }
    else
    {
        myobject.Phone = PhoneTextBox.Text;
    }

if this is the case any suggestions on shortening the if statement or creating a function that takes care of it since it will always be the case when using textbox.

3 Answers 3

2

You could define this extension member:

public static class Extensions
{
    public static string ToNullIfEmpty(this string @this)
    {
        return String.IsNullOrEmpty(@this) ? null : @this;
    }
}

And then you could do this:

myobject.Phone = PhoneTextBox.Text.ToNullIfEmpty();
Sign up to request clarification or add additional context in comments.

Comments

0

If PhoneTextBox.Text is an empty string and not null then, yes, you'll need to explicitly set a null value where you need one. You can shorten it a little bit by using the conditional operator:

myobject.Phone = string.IsNullOrEmpty(PhoneTextBox.Text) ? null : PhoneTextBox.Text;

Comments

0

What method are you using to store the data? Entity Framework or your own stored procedure or sql insert?

If you are rolling your own DAL then you must check for string.IsEmpty, in which case you can use DBNull.Value as the value to pass.

1 Comment

I am using EF DB First

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.