Update Model From Database (Database First)

Update: As this is still relatively popular, I have created a blog post on this.

http://jnye.co/Posts/19/adding-validation-to-models-created-by-entity-framework-database-first-c

If you want to validate your models, and not use viewModels, use partial classes to define validation attributes. For example:

Say you have a model like

public class User {
    public string Name { get; set; }
}

If you wanted to put a string length validator on it you would need to create a partial class and utilise the MetadataTypeAttribute (this lives in System.ComponentModel.DataAnnotations)

The following classes should be defined in their own separate file, NOT put in the same file as your auto generated models.

[MetadataTypeAttribute(typeof(UserMetadata))]
public partial class User {
}

You then define your validation in the UserMetadata class as follows

public class UserMetadata{
    [StringLength(50)]
    public string Name {get; set;}
}

EDIT

I just found this article which explains the solution in a little more detail http://themonitoringguy.com/tips-tricks/validating-microsoft-entity-framework-objects-c-mvc/


No, the files will be regenerated every time.

All the classes are defined as partial so you can easily add DataAnnotations using the MetadataTypeAttribute.

Let's say you have a User class defined as follow:

public partial class User {
    public string Name {get;set;}
}

Create a IUser interface

public interface IUser {
   [Required]
   [DisplayName("User name")]
   string Name {get;set;}
}

And then extend the User class to specify that IUser will be used as metadata.

[MetadataType(typeof(IUser))]
public partial class User {} //Empty class body