Attaching validation to EF objects used in MVC controllers/views?

前端 未结 3 1179
青春惊慌失措
青春惊慌失措 2021-01-21 04:26

We\'re throwing together a quick project (CRUD forms) and decided to skip view models and use EF entities directly in controllers and views. Since I\'m not used to this approach

相关标签:
3条回答
  • 2021-01-21 04:38

    This can be done using MetadataType attribute on the Ef generated classes. The EF generates partial classes. So those can be extended and attribute added to it. Then another "buddy class" can be written that can have member decoration. For example

    [MetadataType(typeof(EFGeneratedClass_MetaData))]
    public partial class EFGeneratedClass
    {
    }
    
    public partial class EFGeneratedClass_MetaData
    {
        [Required]
        [Display(Name="Member1 Display")]
        public string Member1 {get; set;}
    }
    
    0 讨论(0)
  • 2021-01-21 04:48

    Easiest thing to do is to use the DataAnnotations attributes that are in the System.ComponentModel.DataAnnotations anmespace.

    MVC respects those and will populate your ModelError collection if any fail. In the case of your example, you could add a using statement for that namespace and then just flag a property with

    [StringLength(25)]
    

    and call it a day.

    0 讨论(0)
  • 2021-01-21 04:58

    You need to use a partial 'buddy' meta class and decorate it with validation attributes.

    For example, say your entity was 'Foo':

    [MetadataType(typeof(FooMetadata))]
    public partial class Foo {}
    
    public class FooMetadata
    {
        //apply validation attributes to properties
        [Required]
        [Range(0, 25)]
        [DisplayName("Some Neato Property")]
        public int SomeProperty { get; set; }
    }
    

    For more information see this link on MSDN:

    Customize Data Field Validation in the Model

    Cheers.

    0 讨论(0)
提交回复
热议问题