Adding validation to models created by Entity Framework Database First - C#
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.
[MetadataTypeAttribute(typeof(UserMetadata)] is missing one closing ")"
Good spot Erpel, Thanks. I've corrected the post
Thank you :)
Thank you so much.
Thank you very much too.
Excelent!!! Thank you so much!!!!
Hello, one question. The Class With MetadataTypeAttribute need to be Extended from Main model? or how to do it?
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