How to use DataAnnotation with Classes generated through EF ? RRS feed

  • Question

  • User-1700564925 posted

    How to use DataAnnotation with Classes generated through EF ? I have used EF's automatically generated classes as Model for my application and to apply validation inside Forms I need to apply some Annotation inside model classes. If I apply annotation rules inside the classes generated automatically through EF, They get override when I refresh EF model.

    What would be best possible way to apply annotation over such classes ?


    Monday, April 20, 2015 2:11 AM


  • User-821857111 posted

    The best way is to apply data annotations to view models instead of entity classes. If you don't want to use view models, you can use buddy classes. Create a partial class for your entity, and add the MetadataType attribute to it:

    public partial class MyEntity

    Then create a new class file called MyEntityMetadata and apply the annotations to just the relevant properties of your entity:

    public class MyEntityMetadata
        [HiddenInput(DisplayValue = true)]
        public int Id { get; set; }
        [Required, Display(Name = "My Entity Name")]
        public string Name { get; set; }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 20, 2015 5:27 AM