Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 342
Mebourne Avatar asked Oct 12 '12 22:10

Mebourne


1 Answers

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.

like image 114
StriplingWarrior Avatar answered Oct 06 '22 04:10

StriplingWarrior