c# – Validate custom fields from generated classes

Question:

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

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 if the Nome field is empty, ModelState.isValid is always true . Why does it happen? ModelState.isValid should return false .

Answer:

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

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

Scroll to Top