Dataannotation validations do not work on properties with Notmapped attribute in EF6

Asked

Viewed 199 times

0

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

I found that using Dataannotation in the properties of my model that contained the [Notmapped] attribute were causing an exception in Dbentityvalidation.

Commenting on these validations started to work 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; }
}
}

Someone has a solution to this case?

1 answer

0

Hello,

We usually use a standard to meet View needs.

When the View is strongly typed directly with the model we use the so-called Viewmodel.

http://eduardopires.net.br/2013/08/asp-net-mvc-view-model-pattern-quando-e-como-utilizar/

So the View would be strongly typed for Viewmodel, the action would receive an instance from Viewmodel as parameter and the Controller would have the responsibility to convert Viewmodel to Model and so follows the process.

Example View

@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(); 
            ....

Browser other questions tagged

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