Custom validation with MVC2 and EF4

on the ScottGu blog for an example of using MVC2 Custom Validation with EF4: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

So here's the problem:

When a constructor in VS2010 creates objects for a database, for example, you need to add [MetadataType (typeof (Person_validation))] Annotations to this class.

But when I change something in the constructor, all these annotations are lost.

Is it possible to save my own changes to the edmx file, or is it better to apply System.ComponentModel.DataAnnotations to the generated objects?

Thanks.

+2


a source to share


1 answer


You do this with a template called buddy classes. Basically what you do is create a separate class with your metadata and create a partial class that associates the generated objects with your friend class.

For a simple example, let's say you have an object Person

and want to set a property FirstName

. This is what you would be doing outside of your generated files:



[MedadataType(typeof(PersonMetadata))]
partial class Person { } // the other part is generated by EF4

public class PersonMetadata
{
    // All attributes here will be merged into the generated class,
    // thanks to the partial class above. Just apply attributes as usual.

    [Required]
    public string FirstName { get; set; }
}

      

You can find more details on this approach here . And ScottGu actually talks about it too, in the article you linked to. Look under the heading "Step 5: Saving the Database";)

+6


a source







All Articles