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

less than a minute read

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
erpel says:November 17, 2014

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

John says:November 17, 2014

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

Phia says:December 23, 2014

Thank you :)

Lì from Vietnam says:March 10, 2016

Thank you so much.

Triadas says:March 16, 2017

Thank you very much too.

José says:January 17, 2018

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

Maxi says:February 5, 2019

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

Maxi says:February 6, 2019

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