Mebourne
Mebourne

Reputation: 225

EF 5 Is Ignoring [Required] Attribute On Int Type

Entity Framework 5.0.0 seems to ignore the [Required] attribute when included on an int field and automatically includes a 0 value instead of throwing an exception. The required attribute does seem to work if the field is a string though. The simple model and create function below throws no exceptions. DbContext class with DbSet Degrees not shown for brevity.

public class Degree
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Required]
    public int Field { get; set; }
}


private static void CreateDegree()
{
    var degree = new Degree { Name = "Mechanical Engineering" };
    var db = new Context();
    db.Degrees.Add(degree);

    // try statement
}

This maybe a simple misunderstanding on my part, but any thoughts / help would be greatly appreciated.

Upvotes: 8

Views: 4026

Answers (2)

heavyd
heavyd

Reputation: 17751

Your field is of type int which will always have a value. When you create a new instance of the Degree class the Field property will be initialized to 0.

If you want the column to be nullable make the type of the property int?. With a nullable type EF will throw an error if the value is null.

public class Degree
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Required]
    public int? Field { get; set; }
}

Upvotes: 7

StriplingWarrior
StriplingWarrior

Reputation: 156624

The [Required] attribute indicates that a value must be present. When a Degree is constructed, Field is initialized to 0 because that is the default value for ints. Since 0 is a value, it satisfies the [Required] attribute.

You may want to try a [Range] attribute to specify that the value must be greater than 0. Or you could change the model to have an int?, so that it would be null unless it got initialized to some value.

Upvotes: 17

Related Questions