How to define Validation in DB First RRS feed

  • Question

  • For a Project i have a huge Database. This Database i want to use in my ASP.NET MVC 4 Project.

    For tests i defined Data Annotations by some Models to check Validation when save with a form.

    Now my Problem is this:

    When i generate the Model (edmx) its crappy. Some Enities are dubblicated (eg. Person and Persons) the Navigation Propertys are dublicated and so on. I know i can fix this with data annotations. But when i do this and there is a DB Change and a refresh the Model(edmx) the DataAnnotations are lost and i can start at the scratch. 

    My Question:

    How can a use DB First but can define Validation Rules for each Model ?


    Friday, May 31, 2013 6:31 AM


  • Data annotations allows you to describe the rules you want to be applied to your model properties, for example if you want to indicate if a property is required or has a maximum length of n characters. It has nothing to do with removing entities or navigation properties from the entity data model.

    The generated entity classes are created as partial classes which means that you can extend them by creating another partial class for the same entity. For the data annotations not to disappear when you are updating your model from the database and the entity classes are regenerated you should place your validation rules in another partial class called the MetadataType class. Refer to this blogpost for an example: http://ryanhayes.net/blog/data-annotations-for-entity-framework-4-entities-as-an-mvc-model/.

    Friday, May 31, 2013 1:28 PM