EF Core中ObjectContext.MetadataWorkspace等效实现及枚举类型获取问询
EF Core 获取模型所有枚举类型的实现
你提供的代码是否完整?
你给出的写法存在两处遗漏,并不完整:
- 未处理可空枚举类型(如
YourEnum?/Nullable<YourEnum>),这类属性的CLR类型是可空泛型包装类,直接判断ClrType.IsEnum会返回false,导致对应枚举被遗漏 - 若使用EF Core 8及以上版本,
GetEntityTypes()不会返回新增的复杂类型(Complex Type),会漏掉复杂类型中定义的枚举属性;EF Core 8以下版本不存在复杂类型,这部分无问题,且GetEntityTypes()本身已经包含Owned Type,不会遗漏Owned类型的枚举。
EF Core 等效于EF 6的完整实现
首先定义一个辅助方法识别枚举/可空枚举:
private static Type? GetEnumType(Type type) { if (type.IsEnum) return type; var underlyingType = Nullable.GetUnderlyingType(type); return underlyingType?.IsEnum == true ? underlyingType : null; }
适配EF Core 8及以上版本(兼容所有结构类型)
var enumTypes = new List<Type>(); // 遍历所有实体类型(包含普通实体、Owned Type) foreach (var entityType in context.Model.GetEntityTypes()) { enumTypes.AddRange(entityType.GetProperties() .Select(p => GetEnumType(p.ClrType)) .OfType<Type>()); } // 遍历EF Core 8新增的复杂类型 foreach (var complexType in context.Model.GetComplexTypes()) { enumTypes.AddRange(complexType.GetProperties() .Select(p => GetEnumType(p.ClrType)) .OfType<Type>()); } // 去重得到最终所有用到的枚举类型 var distinctEnumTypes = enumTypes.Distinct().ToList();
适配EF Core 1.0 ~ 7.x版本
该版本区间无复杂类型,可简化为:
var distinctEnumTypes = context.Model.GetEntityTypes() .SelectMany(et => et.GetProperties()) .Select(p => GetEnumType(p.ClrType)) .OfType<Type>() .Distinct() .ToList();
EF Core 访问模型所有类型的方法
- EF Core 1.0 ~ 7.x:仅需调用
context.Model.GetEntityTypes(),返回结果包含所有普通实体、Owned Type - EF Core 8及以上:需同时调用
context.Model.GetEntityTypes()和context.Model.GetComplexTypes(),覆盖所有结构类型
内容的提问来源于stack exchange,提问作者D.R.
相关产品推荐
相关产品推荐

