首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 2:實體外部元資料擴展

     編輯:關於ASP.NET

痛點:View Model 與 Business Model 雙維護

View Model 含驗證/顯示屬性(DataAnnotations),Business Model 為持久化實體。兩者高度相似卻需手動映射,架構繁瑣。

解決:MetadataTypeAttribute

System.ComponentModel.DataAnnotations 提供 [MetadataType(typeof(ViewModel))] 標記 Business Model,指定外部元資料類別:

[MetadataType(typeof(Product_Metadata))]
public partial class Product { }

public class Product_Metadata
{
    [Required] public string Name { get; set; }
    [Range(1, 1000)] public decimal Price { get; set; }
}

跨組件擴展問題

若 Business Model 與 MetadataType 不在同一組件,partial class 無法跨組件擴展。需延遲註冊映射關係。

方案:擴展 DataAnnotationsModelMetadataProvider

public static class TypeDescriptorHelper
{
    static Hashtable hashtable = new Hashtable();
    static ReaderWriterLockSlim locker = new ReaderWriterLockSlim();

    public static void RegisterMetadataType(Type type, Type metadataType)
    {
        locker.EnterWriteLock();
        hashtable[type] = metadataType;
        locker.ExitWriteLock();
    }

    public static ICustomTypeDescriptor Get(Type type)
    {
        locker.EnterReadLock();
        var metadataType = hashtable[type] as Type;
        ICustomTypeDescriptor descriptor = null;
        if (metadataType != null)
            descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(type, metadataType).GetTypeDescriptor(type);
        locker.ExitReadLock();
        return descriptor;
    }
}

應用啟動時呼叫 RegisterMetadataType 註冊映射,MVC 模型繫結器透過 GetTypeDescriptor 取得外部元資料,實現跨組件解耦。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved