views:

248

answers:

1

I'm checking out these neat Templated Helpers that have juts been released with the latest preview of ASP.NET MVC.

I notice that I can decorate the classes as required, but I'm thinking it will get a bit messy with Linq 2 Sql if I have to keep re-generating the classes when I make schema changes.

Does any one have a recommended approach of how to take advantage of the Template Helpers but still allow me to use Linq 2 Sql?

+3  A: 

What you are after is a 'Buddy Class'. Scott Gu mentions it in his post for ASP.NET MVC 2 CTP 1 but doesn't go into it.

Anyway, this is my understanding of it. Say you have a Table called Ninja (thanks Phil Haack! ;-) and you obviously have the corresponding linq to sql class that is generated along side all the other linq to sql classes.

What you now need to do is create your own partial class with a 'MetadataType' attribute like so:

[MetadataType(typeof(Ninja_Metadata))]
public partial class Ninja
{
    //Custom model stuff
}

Now you create your 'Buddy Metadata Class' where you can add attributes to properties that are generated by the linq to sql designer:

public class Ninja_Metadata
{
    [DisplayName("Shurikens")]
    public int ShurikenCount { get; set; }
    [DisplayName("Blowgun Darts")]
    public int BlowgunDartCount { get; set; }
}

Sweet feed?

HTHs
Charles

Ps. The use of these 'buddy classes' are also great for adding support for the DataAnnotation Validation attributes.

Charlino
Thanks Charlino, I was thinking along the same lines, but I was uncertain as it seemed like a lot of effort to create a mirror class (as in some cases I guess all properties may require attributes). I guess I could 'gen it up' every time I make changes to the schema.
Dkong
I must admit, I am a bit confused as to why the primary ASP.NET MVC (ie Nerddinner) example used Linq2Sql, then the Preview for ASP.NET MVC 2 templated helpers uses Entity Framework to demonstrate templates due to the fact that Linq2Sql doesn't play as nicely with templates. It's a bit inconsisten IMO
Dkong