Validate custom fields of generated classes

3

To prevent validations made with Data Annotations are lost if the table structure changes, it is necessary to create another class with the fields for validation and a class partial , path that this last class references the class generated by the Entity Framework . And these classes should look like these:

Metadata.cs

namespace BancoDeHoras.Models
{
  public class StatusMetadata
  {
    [Required(ErrorMessage="Nome deve ser preenchido.")]
    public string Nome {set;get;}
  }
}

PartialClasses.cs

namespace BancoDeHoras.Models
{
  [MetadataType(typeof(StatusMetadata))]
  public partial class Status{}
}

Status.cs (generated class)

namespace BancoDeHoras.Data
{
  //usings omitidos

  public partial class Status
  {    
    public int Id { get; set; }
    public string Nome { get; set; }
    public string Descricao { get; set; }
  }
}

Controller

[HttpPost]
public ActionResult Cadastrar(Status status)
{
    if (ModelState.IsValid)
    {
        try
        {
            using (BancoDeHorasEntities banco = new BancoDeHorasEntities())
            {
                banco.Entry(status).State = System.Data.Entity.EntityState.Added;
                banco.SaveChanges();
                TempData["s"] = "Cadastro realizado com sucesso!";
                ModelState.Clear();
                return View();
            }
        }
        catch (Exception)
        {
            TempData["e"] = "Não foi possível cadastrar!";
        }
    }
    return View(status);
}

However, even empty the Nome field, ModelState.isValid is always true . Why does it happen? ModelState.isValid should return false .

    
asked by anonymous 19.05.2015 / 19:49

1 answer

1

The error simply occurred because the namespace of the Metadata.cs and PartialClasses.cs files was not the same as the generated classes are (DataBase.Data) .

The solution was to leave the Metadata.cs and PartialClasses.cs files with namespace BancoDeHoras.Data .

    
19.05.2015 / 20:33