views:

195

answers:

2

I have a linq to sql object or if neccessary Entity Framework object.

I want to do MVC 2 Data Annotations for them, but I am endlessly lazy.

Is there a way to automatically generate the data annotations a-la

[Bind(Include = "Title,Description,EventDate,Address,Country,ContactPhone,Latitude,Longitude")]
[MetadataType(typeof(Dinner_Validation))]
public partial class Dinner
{
    public bool IsHostedBy(string userName)
    {
        return HostedBy.Equals(userName, StringComparison.InvariantCultureIgnoreCase);
    }

    public bool IsUserRegistered(string userName)
    {
        return RSVPs.Any(r => r.AttendeeName.Equals(userName,     StringComparison.InvariantCultureIgnoreCase));
    }
}

public class Dinner_Validation
{
    [Required(ErrorMessage = "Title is required")]
    [StringLength(50, ErrorMessage = "Title may not be longer than 50 characters")]
    public string Title { get; set; }

    [Required(ErrorMessage = "Description is required")]
    [StringLength(265, ErrorMessage = "Description may not be longer than 256 characters")]
    public string Description { get; set; }

    [Required(ErrorMessage = "HostedBy is required")]
    public string HostedBy { get; set; }

    [Required(ErrorMessage = "Address is required")]
    public string Address { get; set; }

    [Required(ErrorMessage = "Country is required")]
    public string Country { get; set; }

    [Required(ErrorMessage = "Phone# is required")]
    public string ContactPhone { get; set; }
}

So that I don't have to do it all myself?

A: 

I think it would be redundant to generate data annotations.

Instead, I'd suggest writing an associated metadata provider which will simply cause the MVC model binding and validation to see the correct metadata for your types without requiring data annotations at all (or will supplement any data annotations you may already have).

There's an example here.

Craig Stuntz
A: 

An example of this for silverlight??

Jaime