views:

583

answers:

1

Hi, on ScottGu's Blog is an Example how to use MVC2 Custom Validation with EF4: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

So here the Problem:

When the Designer in VS2010 creates the Objects for the DB, along to the example you have to add [MetadataType(typeof(Person_validation))] Annotation to that class.

But when i change anything in the Designer all these Annotations are lost.

Is it possible to keep self made changes to the edmx file, or is there any better way of applying System.ComponentModel.DataAnnotations to the generated Entities?

Thanks.

+5  A: 

You do it with a pattern loosely called "buddy classes". Basically what you do is create a separate class with your metadata, and create a partial class that couples the generated entities to your buddy class.

For a simple example, let's say you have a Person entity, and you want to set the FirstName property to be required. This is what you'd do 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 headline "Step 5: Persisting to a database" ;)

Tomas Lycken
thanks for your answer, but the question is more about the part:[MedadataType(typeof(PersonMetadata))]partial class Person { } // the other part is generated by EF4Buddy class with Annotations are working fine. But my problem is: I have about 100 entities. if i do a minor change in the designer in visual studio the code is regenerated. so all the annotations [MedadataType(typeof(....))] referencing to the buddy class are gone. so if i just add an attribute i can go and add on 100 classes the annotation again. not quite the idea of a generation with EF.
csharpnoob
@csharpnoob - It sounds as if you're adding the `MetadataTypeAttribute` to the wrong parts of the partial classes. The idea is that since EF generates partial classes, you can write *your own* parts in *different files* that are *not* regenerated, where you apply the `MetaDataAttribute`. I usually put the partial class applying the attribute in the same file ass the buddy class, so I can instantly see which class(es) will be affected by changes.
Tomas Lycken
damn it. right my fault! annotation on partial, i missed that little detail. this one exisits anyway for setting default values. thanks again.
csharpnoob