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
screen
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

db
LVL 8
CamilliaAsked:
Who is Participating?
 
anarki_jimbelConnect With a Mentor Commented:
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

0
 
MrunalConnect With a Mentor Commented:
Use - AddWithValue

Reference:

 if (value == null)
        cmd.Parameters.AddWithValue(name, DBNull.Value);
    else
        cmd.Parameters.AddWithValue(name, value);
0
 
CamilliaAuthor Commented:
thanks, I'll try it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.