Is there any way to get dataanotations for my models directly from my database? I have a database with lot's of data and tables, so i am generating my model with entity framework from database, so i get classes, but i want to know can entity framework or some other orm get properities and constrains directly from database and put them in classes as data anotation like [required] or [datatype(datatype.emailadress)]
Yes. You can inherit the ModelMetadataProvider class:
public class LocalizedModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
Func<object> modelAccessor, Type modelType, string propertyName)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
if (containerType == null || propertyName == null)
return metadata;
// Load all metadata from your database here.
return metadata;
}
}
I'm creating a project called Griffin.MvcContrib which is almost done and has a administration area where you can handle all localization (zero-code) for both models and validation messages.
By using it you can just implement the following interface to get support for your database:
// the actual code file has detailed explanations of each method.
public interface ILocalizedStringProvider
{
string GetModelString(Type model, string propertyName);
string GetModelString(Type model, string propertyName, string metadataName);
string GetValidationString(Type attributeType);
string GetEnumString(Type enumType, string name);
}
Update
Where is not important. And you do not have to use DataAnnotation attributes on your models (the [Display]
attribute). I just inherit the DataAnnotationsModelMetadataProvider
to be able to use the attributes.
Example:
ModelMetadataProviders.Current = new YourModelMetadataProvider();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.