简体   繁体   English

ASP.NET MVC的模型数据注释

[英]Model DataAnnotation for asp.net mvc

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)] 我有一个包含大量数据和表的数据库,所以我用数据库的实体框架生成我的模型,所以我得到了类,但是我想知道实体框架或其他一些ORM是否可以直接从数据库中获取特性和约束并将它们放入在类中作为数据注释,例如[required]或[datatype(datatype.emailadress)]

Yes. 是。 You can inherit the ModelMetadataProvider class: 您可以继承ModelMetadataProvider类:

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. 我正在创建一个名为Griffin.MvcContrib的项目,该项目已完成,并具有一个管理区域,您可以在其中处理模型和验证消息的所有本地化(零代码)。

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). 而且,您不必在模型上使用DataAnnotation属性( [Display]属性)。 I just inherit the DataAnnotationsModelMetadataProvider to be able to use the attributes. 我只是继承了DataAnnotationsModelMetadataProvider以便能够使用属性。

  1. Create the class anywhere. 在任何地方创建课程。
  2. Read from the database 从数据库中读取
  3. Configure MVC to use it in global.asax 配置MVC以在global.asax中使用它

Example: 例:

 ModelMetadataProviders.Current = new YourModelMetadataProvider();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM