Adding validation to models created by Entity Framework Database First - C#

by John Nye

07 Nov

If you want to validate your entity framework models but still automatically generate your models using entity framework database-first then you need to use a partial classes to define validation attributes. For example:

Say you have the following model

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 utilize the MetadataTypeAttribute (this lives in System.ComponentModel.DataAnnotations)

The following classes should be defined in its own separate file, NOT in the same file as your auto generated models as these will be removed whenever your models are regenerated.

public partial class User {

The above code defines that the metadata should be retrieved from a 'UserMetadata' class which should be defined as below. Again, this should not be placed in the auto generated file produced by entity framework.

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

From now on if you try to create or update a user with a name that has more than 50 characters, validation will fail.

Comments 5

erpel says: 864 days ago

[MetadataTypeAttribute(typeof(UserMetadata)] is missing one closing ")"

John says: 863 days ago

Good spot Erpel, Thanks. I've corrected the post

Phia says: 828 days ago

Thank you :)

Lì from Vietnam says: 385 days ago

Thank you so much.

Triadas says: 14 days ago

Thank you very much too.

Leave a message...

30 Mar