Disable System.CompositionModel.DataAnnotation fro

2019-06-14 18:17发布

问题:

I want to use System.CompositionModel.DataAnnotation for building Model but it should not affect database schema for example if I am using Required then it should not make that column as not nullable in Database. The reason I want to use Data annotation is for MVC 4 JQuery Unobstrusive validation.

As of Now I have applied validation by using

@Html.TextBoxFor(model => model.BookingRequest.Email, new { data_val = "true", data_val_required = "Please provide Special Notes" })

I think this is not best practice or standard way to performing validation.

I want to change my model to something like this.

[Required]
public string Email { get; set; }
public string CustomerName { get; set; }
public string ContactNumber { get; set; }

so that I don't need to pass html attribute while generating the html element in TextAreaFor but in database It should be nullable.

The reason why I am doing this is there is another service which is using same context but it does not provide the email value. And I don't want to change already running services.

I am using EntityTypeConfigurtaion(Fluent API) instead of DataAnnotation for configuring model.

Thanks in advance for your time to review my question.

回答1:

Its not very clear from your explanation which EF approach you are using , here is my solution to DB first approach with entity framework :

add your validation attributes aka Dataanotation with same properties you are going to use in model-db

  public partial class XContent
    {
        [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Resource))]
        [RegularExpression(@"^[a-zA-Z]+$", ErrorMessageResourceName = "UseLettersOnly", ErrorMessageResourceType = typeof(Resource))]
        public string FullName { get; set; }
}

and create a partial class with same modal name and add metadata attribute to use above class

    [MetadataType(typeof(XContent))]
    public partial class YourModelClassName
    {
        public string FullName { get; set; }
    }

so in an all

you have to add two classes one for mapping two classes and second which actually contains data-annotations

I hope that helps !!