在EF Core中获取元数据:表和列映射 [英] Getting metadata in EF Core: table and column mappings
问题描述
希望在EF Core中获取元数据,以处理对象和对象的映射。数据库表的属性
这些映射是在DBContext.cs OnModelCreating()方法,具有.ToTable()的表以及通过.Property.HasColumnName()的列中定义的。 / p>
但是我没有在...返回的实体类型下看到此元数据。
IEnumerable< IEntityType> entityTypes = [dbContext] .Model.GetEntityTypes();
此元数据在EF Core中是否可用?
此元数据在EF Core中是否可用?
<是的。除了属性外,还要检查方法( GetXXX
, FindXXX
等)。并特别注意 Relational()
扩展方法。
例如:
foreach(dbContext.Model.GetEntityTypes()中的var entityType)
{
var tableName = entityType.Relational()。TableName;
foreach(entityType.GetProperties()中的var propertyType)
{
var columnName = propertyType.Relational()。ColumnName;
}
}
您需要具有 Microsoft.EntityFrameworkCore。关系 Nuget软件包已安装。
更新(EF Core 3.0 +): Relational()
提供商扩展已被删除,并且属性已被直接 Get
/ Set
扩展方法替换,因此,列/表名称的代码现在简单地是
var tableName = entityType.GetTableName();
// ..
var columnName = propertyType.GetColumnName();
Looking to get metadata in EF Core, to work with the mappings of objects & properties to database tables & columns.
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();
Is this metadata available anywhere in EF Core?
Is this metadata available anywhere in EF Core?
Yes it is. Just additionally to the properties examine the methods (GetXXX
, FindXXX
etc.). And pay special attention to Relational()
extension methods.
For instance:
foreach (var entityType in dbContext.Model.GetEntityTypes())
{
var tableName = entityType.Relational().TableName;
foreach (var propertyType in entityType.GetProperties())
{
var columnName = propertyType.Relational().ColumnName;
}
}
You need to have Microsoft.EntityFrameworkCore.Relational Nuget package installed.
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屋!