Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

If my MSSQL database contains a data type that is NULL (i.e. null is allowed) th

ID: 644165 • Letter: I

Question

If my MSSQL database contains a data type that is NULL (i.e. null is allowed) then ORMs, such as EntityFramework in my case, create .NET objects that are nullable.

This is great, and the way I use nullables is like this:

C#

int? someInt = 5;

int newInt = someInt.Value; // woot
VB.NET

Dim someInt As Integer?

Dim newInt As Integer = someInt.Value ' hooray
However, recently I had to make a change to the database to make an Id field no longer NULL (nullable). This means that .Value is now broken. This is a nuisance if the Id property is used a lot.

One solution that I thought of is to just use Convert.ToInt32 on Id fields so it doesn't matter if an int is nullable or not.

C#

int newInt = Convert.ToInt32(someInt); // always compiles
VB.NET

Dim newInt As Integer = Convert.ToInt32(someInt) ' always compiles
Is this a bad approach and are there any alternatives?

Explanation / Answer

Well, first off, if a field is nullable, that means it may not have a value. Ints always have a value. If you must for some reason fake a value, then use someNullable.GetValueOrDefault() (which btw, allows a parameter to define the default value).

Secondly, the right thing to do when something goes from sometimes having a value to always having a value, is to refactor it as necessary to represent this new behavior.

Your fundamental problem is that you are trying to treat two entirely seperate scenarios as being the same - one way or another you are probably failing to properly model what is taking place.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote