DataAnnotation Validations Do Not Work on Properties with NotMapped Attribute in EF6

0

I upgraded the Entity Framework version from 5 to 6 in my project, and the Data Repository Context.SaveChanges stopped working in only a few cases.

I found that using DataAnnotation in properties of my template that contained the [NotMapped] attribute were causing an exception in DbEntityValidation.

Commenting on these validations started working again.

using PROJETO.Helper.Generic;
using PROJETO.Helper.Resources;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace PROJETO.Entity.Models
{

[Table("Users")]
public class User
{
    [Key]
    public int UserID { get; set; }

    [Display(Name = "Usuário:")]
    [Required(ErrorMessageResourceName = "UserNameRequired", ErrorMessageResourceType = typeof(CustomMessages))]
    [StringLength(20, MinimumLength = 4, ErrorMessage = "O usuário deve conter no mínimo quatro caracteres e no máximo vinte!")]
    public string UserName { get; set; }

    [Display(Name = "Senha:")]
    [Required(ErrorMessageResourceName = "PasswordRequired", ErrorMessageResourceType = typeof(CustomMessages))]
    [StringLength(20, MinimumLength = 4, ErrorMessageResourceName = "PasswordLength", ErrorMessageResourceType = typeof(CustomMessages))]
    [RegularExpression(@"^((?=.*[a-z])(?=.*[A-Z])(?=.*\d)).+$", ErrorMessageResourceName = "PasswordFormat", ErrorMessageResourceType = typeof(CustomMessages))]
    [CustomValidation.NotEqual("CurrentPassword", ErrorMessageResourceName = "PasswordCompare", ErrorMessageResourceType = typeof(CustomMessages))]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public string Roles { get; set; }

    [NotMapped]
    [Display(Name = "Senha Atual:")]
    //[Required(ErrorMessageResourceName = "CurrentPasswordRequired", ErrorMessageResourceType = typeof(CustomMessages))]
    [DataType(DataType.Password)]
    public string CurrentPassword { get; set; }

    [NotMapped]
    [Display(Name = "Confirmar:")]
    //[Required(ErrorMessage = "Confirme a senha!")]
    //[Compare("Password", ErrorMessageResourceName = "PasswordConfirmCompare", ErrorMessageResourceType = typeof(CustomMessages))]
    [DataType(DataType.Password)]
    public string PasswordConfirm { get; set; }

    [NotMapped]
    [Display(Name = "Manter Conectado")]
    public virtual bool RememberMe { get; set; }
}
}

Does anyone have a solution for this case?

    
asked by anonymous 11.06.2015 / 19:11

1 answer

0

Hello,

We usually use a default to meet View's needs.

Since View is heavily typed directly with the model we use the ViewModel calls.

link

In this way View would be strongly typed to the ViewModel, the action would receive an Instance of the ViewModel as a parameter and the Controller would have the responsibility of converting the ViewModel to the Model and so follow the process.

View Example

@using System.Threading
@using System.Web.Optimization
@model Teste.App.LoginViewModel


@{
    ViewBag.Title = "Dashboard";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm())
{
    <div style="margin:100px 100px 0px 475px;">
    <fieldset style="width:230px">
        <legend>Login do Usuário</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.User)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User)
            @Html.ValidationMessageFor(model => model.User)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>
        <div class="left">
            <div class="editor-field">
                @Html.EditorFor(model => model.Remember)
            </div>
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Remember)
        </div>
        <p>
            <input type="submit" value="Acessar" class="botao" />
        </p>

    </fieldset>
</div>

}

Controller

public class AccountController : Controller
    {
        private readonly IAutorizador _autorizador;

        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Principal");
            }

            return View(new LoginViewModel());
        }

        [HttpPost]
        public ActionResult Index(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            try
            {
               //LoginInfo seria a sua entity de login 
               // O método model.ConvertToEntity() converteria LoginViewModel para LoginInfo 
               LoginInfo entity = model.ConvertToEntity(); 
            ....
    
11.06.2015 / 20:15