SKale
SKale

Reputation: 571

What does Nullable<int> do in an object property?

Recently I decided to do away with the EF "edmx" approach. I just didn't like EF doing things behind the scenes. Initially I had toyed between Code First and Database First because I was not so sure how to use Code First on an existing database. Then I found this great article by Scott Gu (http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx). Now, midway through my development I have switched everything to Code First. And it's working fine.

To save some typing I copied over the models as generated in the .edmx file. That's when I noticed that EF had generated Nullable types for properties especially the related IDs. I probably do not want a foreign key to be null, right? I do not understand why EF would do this? Now that I am using code first, I was thinking I will just remove all these nullable types. This way my views will automatically validate with required fields.

Course model from edmx file:

public class Course
{
    public int CourseId { get; set; }
    public Nullable<int> ProgramId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Type { get; set; }

    public virtual Program Program { get; set; }
}

I would have typed:

public class Course
{
    public int CourseId { get; set; }
    public int ProgramId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Type { get; set; }

    public virtual Program Program { get; set; }
}

On experimentation I realized that removing the nullable automatically enforces required validation on the Program field in my view.

Upvotes: 1

Views: 274

Answers (4)

Nagaraj S
Nagaraj S

Reputation: 13484

Nullable Value Types

ProgramId initially has no defined value, even though the default value of the Integer type is 0.

When you declare a variable with a nullable type, its HasValue property has a 
default value of False. This means that by default the variable has no defined value, 
instead of the default value of its underlying value type.

Upvotes: 1

Ankit Kumar
Ankit Kumar

Reputation: 3723

nullable can be assigned any value from -2147483648(for int32) to 2147483647(for int32), or it can be assigned the null value... . for more details see this http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx

Upvotes: 1

Anthony Chu
Anthony Chu

Reputation: 37530

It means a Course can have an optional Program. Changing it to an int would make it required, as you've already discovered.

Upvotes: 1

TGH
TGH

Reputation: 39268

One argument in favor of the nullable type is that if you forget to specify a value you would get the default int (0) value, which probably isn't desirable. It could in some cases lead to errouneous data in your database if there are no constraints on the db target column

Upvotes: 1

Related Questions