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 a Degree
is constructed, Field
is initialized to 0 because that is the default value for int
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With