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 Objec开发者_如何学编程ts 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.
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" ;)
精彩评论