Mike Marks
Mike Marks

Reputation: 10139

Trying to check to see if my MVC model's value is equal to NULL in my database

Here's the code (please disregard the <p> tags in my <td>, this is just for testing: enter image description here

Right now, I have NULL in my SQL Server database for EarlyDod:

enter image description here

The error I'm getting when comparing item.EarlyDod and DBNull.Value is: enter image description here

I understand this error, and it makes sense, but when I have a NULL value in my database (which I would imagine is DBNull.Value no?), how do I compare my C# object's value item.EarlyDod to check if it's NULL in the database? The value that's coming back from the database via my WebAPI (in JSON format) for EarlyDod is "0001-01-01T00:00:00", not some sort of NULL value, even though it's NULL as you can see in the database.

Upvotes: 1

Views: 1254

Answers (1)

Jonesopolis
Jonesopolis

Reputation: 25370

DateTime is not nullable. So when you are pulling it, it's instantiating the default value for DateTime (DateTime.MinValue)

So you can either convert item.EarlyDod to DateTime?, and use

item.EarlyDod != null

or keep it as a DateTime and simply replace

item.EarlyDod != DBNull.Value

with

item.EarlyDod != DateTime.MinValue 

Upvotes: 4

Related Questions