Specifies a numeric minimum and maximum range for a property
using System.ComponentModel.DataAnnotations;
public partial class Enrollment
{
public int EnrollmentID { get; set; }
[Range(0, 4)]
public Nullable<decimal> Grade { get; set; }
}
If we try to insert/update a Grade with value out of range, this commit will fail. We’ll get a DbUpdateConcurrencyException
that we'll need to handle.
using (var db = new ApplicationDbContext())
{
db.Enrollments.Add(new Enrollment() { Grade = 1000 });
try
{
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Validation failed for one or more entities
}
}
It can also be used with asp.net-mvc as a validation attribute.
Result: