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 8

erpel says: 3240 days ago

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

John says: 3240 days ago

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

Phia says: 3204 days ago

Thank you :)

Lì from Vietnam says: 2762 days ago

Thank you so much.

Triadas says: 2390 days ago

Thank you very much too.

José says: 2083 days ago

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

Maxi says: 1699 days ago

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

Maxi says: 1698 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...

02 Oct