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

by John Nye

07 Nov
2013

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.

[MetadataTypeAttribute(typeof(UserMetadata))]
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{
    [StringLength(50)]
    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 8

erpel says: 3438 days ago

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

John says: 3437 days ago

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

Phia says: 3402 days ago

Thank you :)

Lì from Vietnam says: 2959 days ago

Thank you so much.

Triadas says: 2588 days ago

Thank you very much too.

José says: 2280 days ago

Excelent!!! Thank you so much!!!!

Maxi says: 1897 days ago

Hello, one question. The Class With MetadataTypeAttribute need to be Extended from Main model? or how to do it?

Maxi says: 1896 days ago

To Fix the problem about cant create Class with same name in the same namespace , create a Class xyz in a Folder, and change the NameSpace to the Same ModelEntitie xyz

Leave a message...

16 Apr
2024