0
有什麼辦法直接從我的數據庫中獲取我的模型的dataanotations? 我有一個數據庫與很多的數據和表,所以我從數據庫生成我的模型與實體框架,所以我得到的類,但我想知道可以實體框架或一些其他ORM直接從數據庫中獲得性質和約束,並把他們在類作爲像數據anotation [需要]或[數據類型(datatype.emailadress)]asp.net mvc的模型數據anotation mvc
有什麼辦法直接從我的數據庫中獲取我的模型的dataanotations? 我有一個數據庫與很多的數據和表,所以我從數據庫生成我的模型與實體框架,所以我得到的類,但我想知道可以實體框架或一些其他ORM直接從數據庫中獲得性質和約束,並把他們在類作爲像數據anotation [需要]或[數據類型(datatype.emailadress)]asp.net mvc的模型數據anotation mvc
是。你可以繼承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;
}
}
我創建了一個名爲Griffin.MvcContrib項目,該項目幾乎已經完成,並具有管理區域,您可以處理兩個模型和驗證消息的所有本地化(零代碼)。
通過使用它你可以實現以下接口能得到您的數據庫支持:
// 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);
}
更新
在哪裏並不重要。而且,您不必在模型上使用DataAnnotation屬性([Display]
屬性)。我只是繼承DataAnnotationsModelMetadataProvider
才能夠使用這些屬性。
例子:
ModelMetadataProviders.Current = new YourModelMetadataProvider();
我產生在我的解決方案在單獨的項目我的模型類,所以在我的模型文件夾在mvc解決方案中,我從生成的類中添加新類和複製代碼,並添加手動數據偏移。 那麼你可以更具體地說我應該繼承modelmetadataProvider類嗎? – GoranB
閱讀我的更新。 – jgauffin
你能否請在步驟2)從數據庫中讀取一些更多的信息和3)我從來沒有做過這樣的事情,所以我有點困惑,我應該創建我的ModelMetaDataProvide類? – GoranB