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

We are building a quick project (CRUD forms) and decided to skip view models and use EF objects directly in controllers and views. Since I'm not used to such an approach, I am confused by the validation processing.

For example: the DB field has a length of 25. How is this transmitted (if possible) a check constraint in my view? If I used an intermediate model, I would bind the attributes to the properties of the model, and that would work. How do I do this using EF objects directly? Thank you

+3
source share
3 answers

This can be done using the MetadataType attribute for the classes generated by Ef. EF generates partial classes. In this way, they can be extended and attributes added. Then another “class of friends” can be written, which may have a party 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;} } 
+7
source

The simplest thing is to use the DataAnnotations attributes that are in the System.ComponentModel.DataAnnotations namespace.

MVC respects them and populates your ModelError collection if any failure occurs. In the case of your example, you can add a using statement for this namespace, and then just mark the property with

 [StringLength(25)] 

and call it day.

0
source

You need to use the partial buddy meta-class and decorate it with validation attributes.

For example, let's 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:

Configure data field validation in the model

Greetings.

0
source

All Articles