如何在EF Core Code First模式下访问实体类型信息?
在EF Core Code-First模式中访问实体类型元数据的方法
不管是用普通C#代码还是T4模板,核心都是通过Microsoft.EntityFrameworkCore.Metadata.IModel接口获取实体的元数据(包括实体名称、常规属性、导航属性等),这和Database-First反向工程时使用的元数据结构完全一致。
一、普通C#代码中获取实体元数据
直接从你的DbContext实例中获取IModel,再遍历其中的实体类型及属性:
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; // 替换为你的DbContext类型 using var dbContext = new YourDbContext(); IModel model = dbContext.Model; // 遍历所有实体类型 foreach (IEntityType entityType in model.GetEntityTypes()) { // 获取实体名称(DisplayName带命名空间,ShortName为短名称) Console.WriteLine($"实体:{entityType.DisplayName()}"); // 获取常规属性(非导航属性) Console.WriteLine("常规属性:"); foreach (IProperty property in entityType.GetProperties()) { Console.WriteLine($"- {property.Name}(CLR类型:{property.ClrType.Name})"); } // 获取导航属性 Console.WriteLine("导航属性:"); foreach (INavigation navigation in entityType.GetNavigations()) { string navType = navigation.IsCollection ? "集合" : "单个实体"; Console.WriteLine($"- {navigation.Name}(关联实体:{navigation.TargetEntityType.DisplayName()},类型:{navType})"); } Console.WriteLine("---"); }
关键API说明:
model.GetEntityTypes():获取模型中所有注册的实体类型entityType.DisplayName()/entityType.ShortName():获取实体的显示名称entityType.GetProperties():获取实体的所有常规属性(排除导航属性)entityType.GetNavigations():获取实体的所有导航属性,通过IsCollection判断导航类型
二、T4模板中获取实体元数据
EF Core 7及以上版本的T4模板可直接使用传入的Model参数(类型为IModel),操作逻辑和普通C#代码一致:
<#@ template language="C#" #> <#@ parameter name="Model" type="Microsoft.EntityFrameworkCore.Metadata.IModel" #> <#@ assembly name="Microsoft.EntityFrameworkCore" #> <#@ assembly name="Microsoft.EntityFrameworkCore.Abstractions" #> <#@ import namespace="Microsoft.EntityFrameworkCore.Metadata" #> # 实体元数据清单 <# foreach (var entityType in Model.GetEntityTypes()) { #> --- ## <#= entityType.DisplayName() #> ### 常规属性 <# foreach (var property in entityType.GetProperties()) { #> - <#= property.Name #>(CLR类型:<#= property.ClrType.Name #>) <# } #> ### 导航属性 <# foreach (var navigation in entityType.GetNavigations()) { #> - <#= navigation.Name #>(关联实体:<#= navigation.TargetEntityType.DisplayName() #>,导航类型:<#= navigation.IsCollection ? "集合" : "单个实体" #>) <# } #> <# } #>
注意:模板中需要引用EF Core的相关程序集,并导入Microsoft.EntityFrameworkCore.Metadata命名空间,才能正常访问元数据API。
内容的提问来源于stack exchange,提问作者John Cummings
相关产品推荐
相关产品推荐

