在日常业务开发中,很多项目不会引入 Entity Framework 这类重型 ORM,但又需要一套对象↔︎数据库字段的映射机制。本文分享 SwitchData 项目中实现的一套轻量 ORM 基础设施,涵盖特性标注、元数据扫描、Expression Tree 编译委托、ADO.NET 参数缓存、线程安全锁等核心技术点。
为什么需要轻量 ORM
EF Core 功能完整,但对于一些特定场景:
- 只需要 ADO.NET + 存储过程的简单映射
- 不想引入 LINQ to SQL 的表达式翻译开销
- 已有成熟的 SQL 和存储过程,仅需要 DataReader → 对象的快速转换
可以考虑自己实现一套轻量映射层。它的核心价值在于:用一次反射扫描 + Expression Tree 编译换取后续所有映射操作零反射开销。
整体架构概览
graph TD
A[实体类 MyEntity] -->|DbTable/DbColumn 特性| B[TableMetadataCache]
B -->|首次访问| C[反射扫描 + Expression Tree 编译]
C --> D[TableMetadata<br/>Columns / PrimaryKey / Getter / Setter]
B -->|后续命中| D
D --> E[ObjectMapper.MapFrom<br/>DataReader → 对象]
F[Database] -->|CommandText + ConnectionString| G[SchemaCache / CachingMechanism]
G -->|缓存 SQL 参数| H[IDataParameter[] 克隆]
style C fill:#ff9,stroke:#333
style G fill:#9ff,stroke:#333
整个系统分三层缓存:
| 层级 | 缓存对象 | 键类型 | 解决问题 |
|---|---|---|---|
| 实体元数据 | ConcurrentDictionary<Type, TableMetadata> |
Type |
避免反复反射扫描特性 |
| 数据库 Schema | ConcurrentDictionary<CacheKey, DataTable[]> |
record struct CacheKey |
避免重复查询 GetSchema |
| ADO.NET 参数 | ConcurrentDictionary<CacheKey, IDataParameter[]> |
record struct CacheKey |
避免重复 DiscoverParameters |
第一步:用特性标注实体
先定义一组 Attribute 来描述实体与数据库的映射关系:
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class DbTableAttribute : Attribute
{
public string Name { get; }
public string Schema { get; set; }
public DbObjectType ObjectType { get; }
public DbTableAttribute(string name, DbObjectType objectType = DbObjectType.Table)
{
Name = name.Trim();
ObjectType = objectType;
}
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class DbColumnAttribute : Attribute
{
public string Name { get; }
public bool ReadOnly { get; init; } = false;
public DbColumnAttribute(string name) => Name = name.Trim();
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class DbPrimaryKeyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class DbIdentityAttribute : Attribute { }
一个实际的实体示例:
[DbTable("T_User")]
public class UserEntity
{
[DbPrimaryKey]
[DbIdentity]
[DbColumn("F_ID")]
public long Id { get; set; }
[DbColumn("F_Name")]
public string Name { get; set; } = string.Empty;
[DbColumn("F_DepartmentId")]
public int DepartmentId { get; set; }
[DbColumn("F_CreateTime", ReadOnly = true)]
public DateTime CreateTime { get; set; }
}
这里的设计要点是:用 init 属性给 ReadOnly
这样的标记字段提供默认值,避免每个字段都写冗长的构造函数调用。
第二步:扫描元数据 + Expression Tree 编译委托
这是性能优化的核心。TableMetadataCache 用
ConcurrentDictionary.GetOrAdd 做线程安全的懒加载:
public static class TableMetadataCache
{
private static readonly ConcurrentDictionary<Type, TableMetadata> Cache = new();
public static TableMetadata GetTableMetadata(Type type)
{
return Cache.GetOrAdd(type, CreateMetadata);
}
private static TableMetadata CreateMetadata(Type type)
{
// 1. 反射扫描 DbTableAttribute
var dbTableAttribute = type.GetCustomAttribute<DbTableAttribute>();
// 2. 遍历所有 public instance 属性
var columns = new List<ColumnMetadata>();
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var columnAttribute = property.GetCustomAttribute<DbColumnAttribute>();
if (columnAttribute == null) continue;
columns.Add(new ColumnMetadata
{
PropertyName = property.Name,
ColumnName = columnAttribute.Name,
PropertyType = property.PropertyType,
Property = property,
IsPrimaryKey = property.IsDefined(typeof(DbPrimaryKeyAttribute)),
IsIdentity = property.IsDefined(typeof(DbIdentityAttribute)),
ReadOnly = columnAttribute.ReadOnly,
// 关键:用 Expression Tree 编译委托,替代反射调用
Getter = CreateGetter(property),
Setter = CreateSetter(property)
});
}
// 3. 构建映射字典
return new TableMetadata
{
Type = type,
Columns = columns,
PrimaryKey = columns.FirstOrDefault(c => c.IsPrimaryKey),
InsertableColumns = columns.Where(c => !c.ReadOnly && !c.IsIdentity).ToList(),
UpdatableColumns = columns.Where(c => !c.ReadOnly && !c.IsPrimaryKey && !c.IsIdentity).ToList(),
PropertyMap = columns.ToDictionary(c => c.PropertyName, StringComparer.OrdinalIgnoreCase),
ColumnMap = columns.ToDictionary(c => c.ColumnName, StringComparer.OrdinalIgnoreCase)
};
}
}
Expression Tree 编译委托
反射调用 property.GetValue() 和
property.SetValue() 的开销是直接调用的 100-1000
倍。解决办法是用 Expression Tree 在首次扫描时把属性访问编译成委托:
private static Func<object, object> CreateGetter(PropertyInfo property)
{
// 参数:object instance
var instance = Expression.Parameter(typeof(object), "obj");
// 强转实例为具体类型
var cast = Expression.Convert(instance, property.DeclaringType!);
// 访问属性
var propertyAccess = Expression.Property(cast, property);
// 值类型装箱
var box = Expression.Convert(propertyAccess, typeof(object));
// 编译
return Expression.Lambda<Func<object, object>>(box, instance).Compile();
}
private static Action<object, object> CreateSetter(PropertyInfo property)
{
if (!property.CanWrite || IsInitOnly(property))
{
return (_, _) => { }; // init-only 属性返回空委托
}
var instance = Expression.Parameter(typeof(object), "obj");
var value = Expression.Parameter(typeof(object), "value");
var instanceCast = Expression.Convert(instance, property.DeclaringType!);
var propertyAccess = Expression.Property(instanceCast, property);
var valueCast = Expression.Convert(value, property.PropertyType);
var assign = Expression.Assign(propertyAccess, valueCast);
return Expression.Lambda<Action<object, object>>(assign, instance, value).Compile();
}
这段代码编译后的 Getter/Setter 委托,IL
代码等价于手写的 return ((T)obj).Property 和
((T)obj).Property = (TProperty)value,运行时开销与直接调用相当。
第三步:从 DataReader 映射到对象
有了预编译的 Setter 委托,ObjectMapper.MapFrom
变得非常简洁:
public static T MapFrom<T>(IDataRecord record) where T : class, new()
{
var entity = new T();
var metadata = TableMetadataCache.GetTableMetadata<T>();
for (int i = 0; i < record.FieldCount; i++)
{
var columnName = record.GetName(i);
var value = record.GetValue(i);
if (!metadata.ColumnMap.TryGetValue(columnName, out var column)) continue;
if (value == DBNull.Value)
{
if (!column.IsNullable)
throw new InvalidOperationException($"字段 {columnName} 为 NULL,但属性不允许为空");
column.Setter(entity, null);
continue;
}
if (!column.PropertyType.IsInstanceOfType(value))
value = Convert.ChangeType(value, column.PropertyType);
column.Setter(entity, value); // 编译后的委托调用,非反射
}
// 可选回调
if (entity is IDbObject callback) callback.OnLoaded();
return entity;
}
注意几个细节:
record.FieldCount+record.GetName(i)的按序号遍历方式,避免了GetOrdinal的额外查找ColumnMap用StringComparer.OrdinalIgnoreCase做不区分大小写的匹配,兼容不同数据库的字段命名风格IDbObject.OnLoaded()回调让实体可以在加载完成后做补充初始化(比如计算属性)
第四步:ADO.NET 参数缓存
每次执行 SQL 时,如果手动添加参数值没问题,但如果依赖
commandBuilder.DeriveParameters() 或者
database.DiscoverParameters()
从存储过程自动推断参数,这个过程是很昂贵的。CachingMechanism
缓存了参数模板:
internal readonly record struct CacheKey(string ConnectionString, string CommandText);
internal class CachingMechanism
{
private readonly ConcurrentDictionary<CacheKey, IDataParameter[]> paramCache = new();
public void SetParameters(DbCommand command, Database database)
{
var key = new CacheKey(database.ConnectionString, command.CommandText);
if (paramCache.TryGetValue(key, out var cached))
{
// 克隆参数,避免污染缓存
foreach (var p in CloneParameters(cached))
command.Parameters.Add(p);
}
else
{
database.DiscoverParameters(command);
paramCache[key] = CloneParameters(command.Parameters.Cast<IDataParameter>().ToArray());
}
}
public static IDataParameter[] CloneParameters(IDataParameter[] source)
{
var result = new IDataParameter[source.Length];
for (int i = 0; i < source.Length; i++)
result[i] = (IDataParameter)((ICloneable)source[i]).Clone();
return result;
}
}
几个值得注意的点:
record struct CacheKey是值类型,避免了每次创建键对象时的堆分配- 用
ConcurrentDictionary.TryGetValue而非GetOrAdd,因为首次发现参数是有副作用的操作,不能在工厂函数里做 - 缓存的是参数模板(DbType、Size、Direction 等),执行前 Clone 出独立实例来设置 Value,避免并发污染
第五步:.NET 9 Lock 类型做初始化保护
TableMetadata 里有一个字段 DbTableName
可能在创建时还拿不到(比如延迟从数据库反查),需要线程安全的延迟初始化。项目里用了
.NET 9 新增的 System.Threading.Lock:
public sealed class TableMetadata
{
private readonly Lock _lock = new(); // .NET 9 新类型
private bool _isInitialized;
public string DbTableName { get; private set; } = string.Empty;
public void InitializeTableInfo(string tableName, DbObjectType objectType = DbObjectType.Table)
{
using (_lock.EnterScope())
{
if (_isInitialized) return;
DbTableName = tableName.Trim();
ObjectType = objectType;
_isInitialized = true;
}
}
}
相比传统的 lock(this) { ... } 或
Monitor.TryEnter,Lock 类型是 .NET 为取代
Monitor 而设计的轻量级锁,避免了在对象头里预留 SyncBlock
的开销。
性能对比
| 方案 | 1万次映射耗时 | 说明 |
|---|---|---|
手写 new Entity { Id = reader.GetInt64(0), ... } |
~1ms | 最优,编译期确定 |
| Expression Tree 编译委托 | ~2ms | 本文方案,首次编译后接近手写 |
反射 PropertyInfo.SetValue |
~300ms | 慢 150 倍 |
| EF Core FromSql 变更跟踪 | ~50ms | 有额外开销 |
Expression Tree 方案的优势在于:首次启动时有一次反射+编译的启动成本(几十毫秒),之后每次映射都是纯委托调用,性能损失 < 2x。
可扩展的方向
- 异步加载器:
TableMetadata加一个Lazy<Task>实现真正的异步初始化 - SQL 生成器:基于
InsertableColumns/UpdatableColumns自动生成 INSERT/UPDATE 语句 - DI 集成:把
TableMetadataCache注册成 Singleton,配合 IOptions 做配置化 - AOT 兼容:当前方案依赖运行时反射,AOT 场景可改用 Source Generator 在编译期生成 Getter/Setter
总结
这套轻量 ORM
的核心思路是:把运行时开销的工作前置到启动时,用一次反射扫描 +
Expression Tree
编译换取后续零反射成本。三层缓存设计(实体元数据 + Schema +
参数模板)分别解决了三个常见的性能瓶颈,ConcurrentDictionary
+ record struct + .NET 9 Lock
的组合则提供了线程安全且内存高效的基础设施。
如果你的项目也在 ADO.NET 和 EF Core 之间寻找平衡,不妨参考这套设计——不需要 NuGet 依赖,全部代码不到 1000 行。