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

LINQ to SQL 實現動態表名映射:透過 MappingSource 自訂對應

     編輯:關於.NET

問題:實體類別對應資料表時,[Table(Name="User")] 寫死表名。實務上可能需依情境動態加前綴/後綴(如 tt_User、User1)。

分析:DataContext 透過 MappingSource 取得對應資訊。解決方法是繼承 MappingSource 自訂模型。

解決方案:實作 DynamicMappingSource 覆寫 CreateModel,內部 DynamicAttributedMetaModel 覆寫 GetTable,根據委派 GetMetaTableName 動態產生 TableAttribute 並建立 MetaTable。

class DynamicMappingSource : MappingSource {
    public Func<Type, string> GetMetaTableName;
    protected override MetaModel CreateModel(Type dataContextType) {
        return new DynamicAttributedMetaModel(this, dataContextType);
    }
    class DynamicAttributedMetaModel : MetaModel {
        // ... 透過反射建立 AttributedMetaTable,注入動態表名
        public override MetaTable GetTable(Type rowType) {
            if (mappingSource.GetMetaTableName != null) {
                var attr = new TableAttribute { Name = mappingSource.GetMetaTableName(rowType) };
                // 反射建立 MetaTable 實例
            }
            return source.GetTable(rowType);
        }
    }
}

使用範例:

var mappingSource = new DynamicMappingSource();
int i = 0;
mappingSource.GetMetaTableName = t => {
    var att = (TableAttribute)t.GetCustomAttributes(typeof(TableAttribute), true).Single();
    return att.Name + i;
};
var context = new DataContext(connStr, mappingSource) { Log = Console.Out };
i = 1; context.GetTable<User>().ToList(); // 查詢 User1
i = 2; context.GetTable<User>().ToList(); // 查詢 User2

結果:SQL 語句顯示表名已動態變為 User1、User2。
動態表名查詢結果

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