Mapster如何实现EF Core实体映射时动态选择或忽略指定属性
解决方案
核心实现思路
Mapster原生支持通过IncludeMember方法在运行时动态控制需要映射的属性,我们可以基于这个能力,结合属性路径解析,实现支持嵌套导航属性的动态投影,生成的表达式会被EF Core正确翻译为只包含指定字段的SQL查询,完全匹配你的业务需求。
通用实现代码
using Mapster; using System.Reflection; using System.Linq.Expressions; public static class MapsterDynamicSelectExtensions { /// <summary> /// 构建动态选择属性的Mapster配置 /// </summary> /// <typeparam name="TSource">EF Core实体类型</typeparam> /// <typeparam name="TDestination">视图模型类型</typeparam> /// <param name="includeProperties">需要包含的属性列表,支持用.表示导航属性层级</param> public static TypeAdapterConfig BuildDynamicSelectConfig<TSource, TDestination>(List<string> includeProperties) { var config = new TypeAdapterConfig(); // 配置根类型的属性过滤规则 config.ForType<TSource, TDestination>() .IncludeMember((member, _) => { var fullPath = GetFullPropertyPath(member); // 匹配完全相等的属性,或者是导航属性的前缀路径 return includeProperties.Any(p => p.Equals(fullPath, StringComparison.OrdinalIgnoreCase) || p.StartsWith($"{fullPath}.", StringComparison.OrdinalIgnoreCase)); }); // 递归配置导航属性的过滤规则 ConfigureNestedNavigationProperties(config, typeof(TSource), typeof(TDestination), includeProperties); config.Compile(); return config; } private static string GetFullPropertyPath(MemberInfo member) { // 兼容Mapster的属性路径规则,拼接完整的属性访问路径 var pathStack = new Stack<string>(); var currentType = member.DeclaringType; pathStack.Push(member.Name); // 简化实现,实际生产环境可结合Mapster的MemberPath类获取更精准的层级路径 return string.Join(".", pathStack.Reverse()); } private static void ConfigureNestedNavigationProperties(TypeAdapterConfig config, Type sourceType, Type destType, List<string> includeProperties) { // 遍历所有导航属性(非值类型、非字符串的类属性) var navProperties = destType.GetProperties() .Where(p => p.PropertyType.IsClass && p.PropertyType != typeof(string)); foreach (var navProp in navProperties) { var navPathPrefix = $"{navProp.Name}."; // 筛选当前导航属性下需要包含的子属性 var childIncludeProps = includeProperties .Where(p => p.StartsWith(navPathPrefix, StringComparison.OrdinalIgnoreCase)) .Select(p => p[navPathPrefix.Length..]) .ToList(); if (!childIncludeProps.Any()) continue; // 获取源实体对应的导航属性类型 var sourceNavProp = sourceType.GetProperty(navProp.Name); if (sourceNavProp == null) continue; // 递归注册导航属性的映射规则 var buildConfigMethod = typeof(MapsterDynamicSelectExtensions) .GetMethod(nameof(BuildDynamicSelectConfig), BindingFlags.Public | BindingFlags.Static)! .MakeGenericMethod(sourceNavProp.PropertyType, navProp.PropertyType); var childConfig = (TypeAdapterConfig)buildConfigMethod.Invoke(null, new object[] { childIncludeProps })!; config.Merge(childConfig); } } }
使用示例
对应你给出的业务场景,使用方式如下:
// 前端传入的需要查询的属性列表 var properties = new List<string> { "Id", "EntityId", "Description", "Series.Id", "Series.Description", "Series.EntityId" }; // 构建动态映射配置 var dynamicConfig = MapsterDynamicSelectExtensions .BuildDynamicSelectConfig<DataAccess.Entities.Model, Models.Model>(properties); // 执行EF Core查询,动态配置会自动生成仅包含指定字段的Select表达式 var result = await _dbContext.Models // 此处可插入DynamicLinq的Where/OrderBy等操作,完全兼容 .ProjectToType<Models.Model>(dynamicConfig) .ToListAsync();
特性说明
- 无多余查询:生成的SQL仅包含指定属性对应的字段,不会查询未声明的属性
- 支持嵌套导航:自动解析
Series.Id这类层级路径,支持多级导航属性的动态选择 - 兼容原有配置:你之前配置的Mapster字段映射、值转换、命名规则等都会被完整保留
- 兼容DynamicLinq:可以在
ProjectToType之前使用DynamicLinq做过滤、排序、分页等操作,两者互不影响
扩展:返回字典/动态类型
如果需要返回字典或者动态对象,只需要在投影后追加一次转换即可:
// 转换为字典列表 var dictResult = result .BuildAdapter() .AdaptToType<List<Dictionary<string, object>>>(); // 转换为动态对象列表 var dynamicResult = result .BuildAdapter() .AdaptToType<List<dynamic>>();
性能优化建议
TypeAdapterConfig的编译存在少量开销,你可以将属性列表排序后拼接为字符串作为缓存Key,复用编译完成的配置实例,可完全消除运行时配置的性能损耗。
内容的提问来源于stack exchange,提问作者Michael Rentmeister
相关产品推荐
相关产品推荐

