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.
The
[Required]attribute indicates that a value must be present. When aDegreeis constructed,Fieldis initialized to 0 because that is the default value forints. 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 anint?, so that it would benullunless it got initialized to some value.