0
votes

I have MVC app with a custom login page. The model is generated by Entity Framework and it's called "User" . When use logs in, the server code updates the login date: user.LoginDate = DateTime.Now; And it works fine.

But now I started applying the validation. What I did is: 1) I created another class, made it partial and named User.cs:

[MetadataType(typeof(UserMetadata))]
public partial class User
{
    [Bind]
    public class UserMetadata
    {
        [DisplayName("Email")]
        [Required(ErrorMessage="Email field is required")]
        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        [StringLength(30)]
        public string UserEmail { get; set; }

        ...

        [Range(typeof(DateTime), "1/1/2010", "2/2/2024", ErrorMessage = "message")]
        public Nullable<System.DateTime> LoginDate { get; set; }
    }
} 

And now I have a problem. When EF tries to update the database, it throws an error about some kinda data validation issue in the code where I'm trying to update the LoginDate field.

If I comment this class, it works fine, no error, but no validation neither.

I thought that maybe it's datetime format, so I also tried the following attribute for a LoginDate field:

       [DataType(DataType.DateTime)]
       [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{yyyy/MM/dd HH:mm:ss tt}")]

Also tried [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{yyyy/MM/dd HH:mm:ss.fff}")]

However, it did not help and it's quite frustrating, because when I look at my database, I see that the LoginDate is written in the proper format: 2014-12-26 19:49:12.247

Please advise.

1
Why you need the validation of the LoginDate? This field is not user's input. Your own server code assigns correct values to it.Mark Shevchenko
In most examples metadata class is external to the class which it describes, could that be a problem. Also, metadata properties are of object type. But I am only guessing here.Darek
End perhaps you don't need metadata after all: remondo.net/entity-framework-code-first-data-annotationsDarek
Mark, I don't really need to validate this field. The reason is the following: The User DB model has around 8 fields. My other user.cs class which I use for validation purpose only initially had only 2 fields where I put the attributes to validate. However I got an error when I tried to update the logindate field, so I decided that this is because my other partial user class missed validation attribute for the field I'm chandingJack Smith

1 Answers

0
votes

I've just fixed the problem. The solution is: I removed "[Bind]" attribute and now it works.