EF 4.1 Code First Validation

When we either use the Fluent API or the attribute to put restrictions to our properties and while adding if we violet that, error would occur. Code First provides us set of classes to capture them

Code First Model

public class Department

{

    [Key]

    public int DeptId { get; set; }

    public string DeptName { get; set; }

 

    public virtual ICollection<Employee> Employees { get; set; }

}

 

public class Employee

{

    [Key]

    public int EmpId { get; set; }

    [MaxLength(3)]

    public string EmpName { get; set; }

    public virtual Department Dept { get; set; }

}

 

public class EmpContext : DbContext

{

    public DbSet<Department> Depts { get; set; }

    public DbSet<Employee> Emps { get; set; }

 

    protected override void OnModelCreating(DbModelBuilder modelBuilder)

    {

        modelBuilder.Entity<Department>().Property(p => p.DeptName).HasMaxLength(2);

    }

}

My Application Code (need to refer the namespace “System.Data.Entity.Validation”)

Database.SetInitializer<EmpContext>(new DropCreateDatabaseIfModelChanges<EmpContext>());

using (var db = new EmpContext())

{

    var d1 = new Department() { DeptName = "IT" };

    var d2 = new Department() { DeptName = "Software" };

 

    new List<Employee>

    {

  new Employee() { EmpName = "Wriju", Dept = d2 },

        new Employee() { EmpName = "Writam", Dept = d2 },

        new Employee() { EmpName = "Sumitra", Dept = d2 },

        new Employee() { EmpName = "Debajyoti", Dept = d2 }

    }.ForEach(e => db.Emps.Add(e));

 

    try

    {

        db.SaveChanges();

    }

    catch (DbEntityValidationException e)

    {

        foreach (var k in e.EntityValidationErrors)

        {

            foreach (var e1 in k.ValidationErrors)

            {

                Console.WriteLine("{0} - {1}", e1.PropertyName, e1.ErrorMessage);

            }

        }

    }

}

Captured Errors

EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
DeptName - The field DeptName must be a string or array type with a maximum length of '2'.
EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
EmpName - The field EmpName must be a string or array type with a maximum length of '3'.
EmpName - The field EmpName must be a string or array type with a maximum length of '3'.

Namoskar!!!