Insert null instead of blank in database

I'll go step by step. I wonder why blank gets inserted instead of null

1. This is in the model
public string MiddleName { get; set; }

Open in new window

2. Database column is this
[MiddleName] [varchar](250) NULL,

Open in new window

3. I don't enter anything in  the middle name field
4.  I have this line of code

 var middleName = string.IsNullOrEmpty(model.MiddleName) ? (object) DBNull.Value : model.MiddleName;

Open in new window

5. I see the value is null
null value
6. I see this after the line of code is executed
value of middle name
7. I call a stored proc and insert it like this. I out .ToString() because I was getting an error that Object can't be converted to string

  _dbContext.usp_InsertPersonali765Draft(model.ApplyReasonId, firstName, middleName.ToString(),

Open in new window

8.  This is part of the stored proc

ALTER procedure [dbo].[usp_InsertPersonali765Draft]

@ApplyReasonId int,
@FirstName varbinary(max),
@MiddleName varchar(50),

Open in new window

9. I see blank . I want to save Null

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

anarki_jimbelSenior DeveloperCommented:
I'd probably modify the stored procedure to insert NULL if middle name is empty.

The thing is that when you call [middleName.ToString] you get an empty string. And you insert this empty string, not NULL into a database.

Or simply try to pass 'null' to the stored procedure.
var middleName = string.IsNullOrEmpty(model.MiddleName) ? null : model.MiddleName;

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Use - AddWithValue


 if (value == null)
        cmd.Parameters.AddWithValue(name, DBNull.Value);
        cmd.Parameters.AddWithValue(name, value);
CamilliaAuthor Commented:
thanks, I'll try it.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.