Posts Tagged ‘ASP.NET’

MVC Buddy Class

26 January 2010 5 comments

My latest “toy” is the new .NET 4.0 and MVC framework which has a few really nice additions.  In this post I will briefly cover one of them, Buddy Classes.  Although there are disagreements as to whether or not this is a good or bad thing, I like the fact that it makes life a bit simpler on smaller projects.

First off I created a VERY simple database with one table.

CREATE TABLE [dbo].[Friend](
	[UserId] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](100) NOT NULL,
	[LastName] [nvarchar](100) NOT NULL,
	[BirthDate] [date] NOT NULL,
	[UserId] ASC


This table will just hold a list of people.  The BrithDate column is not really for this post but for a later one where I will demonstrate how to use user controls for editing specific data types.

Then I added my ADO.NET Entity Data Set, in my Model folder, which created an object for this table.  As we all know, if I change this class the changes will be replace every time it is re-generated.  This is a problem when you want to add some attributes to the class.  What the guys at Microsoft has done is given us a way (hacky some say) to get passed this problem.   With this new feature we can simply create a Buddy Class (normal class in the Model folder) and decorate it to look like this:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace MVCBuddyClass.Models
    public partial class Friend

    public class FriendMeta
        [DisplayName("First Name")]
        public string FirstName { get; set; }
        [DisplayName("Last Name")]
        public string LastName { get; set; }
        [DisplayName("Date of Birth")]
        public DateTime BrithDate { get; set; }

In this code you will notice the public partial class Friend, which has the same name as the partial class generated by the Entity Framework.  My own Friend class in this case gets the attribute [MetadataType(typeof(FriendMeta))] which you need using System.ComponentModel.DataAnnotations; for.  This hooks it up to my “buddy” class, FriendMeta.
FriendMeta contains all the properties with their attributes that we want to set, like DisplayName("First Name")] in this case.  There are many other attributes that you can set which more of will be covered in later posts, this one was simply to display the basic idea of a buddy class.

This should only be used for classes that get auto-generated to keep DRY.