Validate custom fields of generated classes

Asked

Viewed 310 times

3

To prevent validations made with Data Annotations are lost if the table structure changes, it is necessary to create another class with fields for validation and a class partial, path that this last class refers to the class generated by Entity Framework. And these classes should stay 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);
}

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

  • Ever tried to make if (status!= null && ModelState.IsValid) {...}?

  • I tried, but it still wasn’t. The status is not coming null.

  • How you are calling is ACTION in the controller?

1 answer

1


The error simply occurred because the namespace of the archives Metadata.Cs and Partialclasses.Cs was not the same as the generated classes are (Bancodehours.Data).

The solution was to leave the files Metadata.Cs and Partialclasses.Cs with the namespace BancoDeHoras.Data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.