1. Create the poco objects from existing database by using VS 2010.
First, add a new ADO.net Entity Data Model item from the installed templates pane, setting up the database connections and then select your specific model objects from the table list.
Second, open the edmx file in the Entity Designer. Right click to select Add Code Generation Item, from installed templates pane, then select ADO.net DbContext Generator.
Now you have the code-gen poco objects.
2. To create the meta-data classes for those pocos.
First you need to create a partial class of the particular poco object and add attribute (Here is an example of poco object Category)
[MetadataType(typeof(CategoryMetaData))] public partial class Category
Then create an internal sealed class, called CategoryMetaData (which needs to match the attribute).
internal sealed class CategoryMetaData { private CategoryMetaData() { } }
The last thing you need to do, is to put attributes (data annotations) on top of each properties.
[Required] public string Name { get; set; } [StringLength(20)] public string Code { get; set; } [Display(Name="Category Description")] public string Description { get; set; }
Here is the final look of the metadata class,
[MetadataType(typeof(CategoryMetaData))] public partial class Category { internal sealed class CategoryMetaData { private CategoryMetaData() { } [Required] public string Name { get; set; } [StringLength(20)] public string Code { get; set; } [Display(Name="Category Description")] public string Description { get; set; } } }
It is that easy!!
this is something I was looking for, but still not clear: where does the metadata class text above go? separate class file, but then there would be 2 category.cs files ?! pr it is separate as categorymetadata.cs or appended within the Db context generator’s category.cs ? dopey I know but trying this kind of model and generation for the first time.
The metadata class will sit in a different file. You can’t put it inside the generator’s category.cs, your codes will be overwritten when you refresh the model. You can name it differently: categoryMetaData.cs, or place it in different folder with same name “/metadata/category.cs”, but keep the namespace same and partial class of category, such as “Public partial class Category”. Hope this helps. Cheers