在 EF Core 中获取元数据:表和列映射 [英] Getting metadata in EF Core: table and column mappings
问题描述
希望在 EF Core 中获取元数据,以处理对象和对象的映射数据库表的属性 &列.
Looking to get metadata in EF Core, to work with the mappings of objects & properties to database tables & columns.
这些映射在 DBContext.cs OnModelCreating() 方法中定义,使用 .ToTable() 映射表,通过 .Property.HasColumnName() 映射列.
These mappings are defined in the DBContext.cs OnModelCreating() method, mapping tables with .ToTable(), and columns via .Property.HasColumnName().
但是我在...返回的实体类型下没有看到此元数据
But I don't see this metadata under the Entity Types returned by...
IEnumerable<IEntityType> entityTypes = [dbContext].Model.GetEntityTypes();
此元数据是否在 EF Core 中的任何位置可用?
Is this metadata available anywhere in EF Core?
推荐答案
此元数据是否在 EF Core 中的任何位置可用?
Is this metadata available anywhere in EF Core?
是的.除了属性之外,还要检查方法(GetXXX
、FindXXX
等).并特别注意 Relational()
扩展方法.
Yes it is. Just additionally to the properties examine the methods (GetXXX
, FindXXX
etc.). And pay special attention to Relational()
extension methods.
例如:
foreach (var entityType in dbContext.Model.GetEntityTypes())
{
var tableName = entityType.Relational().TableName;
foreach (var propertyType in entityType.GetProperties())
{
var columnName = propertyType.Relational().ColumnName;
}
}
您需要安装 Microsoft.EntityFrameworkCore.Relational Nuget 包.
You need to have Microsoft.EntityFrameworkCore.Relational Nuget package installed.
更新(EF Core 3.0+): Relational()
provider 扩展已被移除 并且属性已被替换为直接Get
/Set
扩展方法,所以列/表名称的代码现在很简单
Update (EF Core 3.0+): Relational()
provider extensions have been removed and properties have been replaced with direct Get
/ Set
extension methods, so the code for column/table names now is simply
var tableName = entityType.GetTableName();
// ..
var columnName = propertyType.GetColumnName();
这篇关于在 EF Core 中获取元数据:表和列映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!