1

I have the following Entity model:

public class Todo  
{  
    [Required]  
    public int ID { get; set; }  
    public int OrderId { get; set; } //Not required  
    public string Description { get; set; }  
    public bool Finished { get; set; }  
    public DateTime CreationDate { get; set; }  
    public int Priority { get; set; } //Not required  
    public string CreatedBy { get; set; }  
    public bool Deleted { get; set; }  
}

In the corresponding database table all of the fields are created as "not null". I want to allow some of the fields to be null. How do I do this?

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
user547311
  • 33
  • 1
  • 4

1 Answers1

9

On the database side, you will have to change the fields you want to be optional so that they can be null. The ALTER TABLE statement will do the trick.

ALTER TABLE Todo
ALTER COLUMN OrderId int NULL

ALTER TABLE Todo
ALTER COLUMN Priority int NULL

On the application side, you need to use nullable types. Try this:

public class Todo
{
    [Required]
    public int ID { get; set; }
    public int? OrderId { get; set; } //Not required
    public string Description { get; set; }
    public bool Finished { get; set; }
    public DateTime CreationDate { get; set; }
    public int? Priority { get; set; } //Not required
    public string CreatedBy { get; set; }
    public bool Deleted { get; set; }
}

A nullable type is a variation of a regular value type with the difference that it can be null. In your code you can test for null with the HasValue property:

int? foo= 42;
Console.WriteLine(foo.HasValue); // prints True
Console.WriteLine(foo.Value); // prints 42
int? bar = null;
Console.WriteLine(bar.HasValue); // prints False
Console.WriteLine(bar.Value); // throws InvalidOperationException

All operators on that type are lifted, meaning that you can still do arithmetic with them:

int? foo = 23;
int? bar = 17;
int? foobar = foo + bar;
Console.WriteLine(foobar); // Prints 40
int? baz = null;
int? foobaz = foo + baz + bar; // If any of them is null, the result will be null.
Console.WriteLine(foobaz); // Prints null
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510