实体框架:获取元数据 IProperty 的 DataType [英] Entity Framework: Get the DataType of Metadata IProperty
问题描述
如何在 Entity Framework Core 中找到 Metadata.IProperty 的 DataType?
How do I find the DataType of Metadata.IProperty in Entity Framework Core?
var tableType = _dbContext.Model.GetEntityTypes().First(c => c.GetTableName() == tableName);
foreach (var property in tableType.GetProperties())
{
var test = property.PropertyInfo.PropertyType.Name;
使用 property.PropertyInfo.PropertyType.Name
,有时有效,但是对于可为空的对象,它会打印 null.我正在寻找一种干净的方法来获取数据类型.
Using property.PropertyInfo.PropertyType.Name
, sometimes works, however for nullable objects it prints null. I am looking for a clean way to get data type.
推荐答案
IProperty
的 Type
由 ClrType
属性表示.它可以正确处理真实属性(具有 PropertyInfo
)、字段(EF Core 5.0+ 允许映射字段 作为属性),以及 shadow 属性,没有关联的 PropertyInfo
或 FieldInfo代码>.
The Type
of the IProperty
is represented by ClrType
property. It handles correctly both real properties (having PropertyInfo
), fields (EF Core 5.0+ allow mapping fields as properties), and also shadow properties which have no assocaited PropertyInfo
or FieldInfo
at all.
var tableType = _dbContext.Model.GetEntityTypes().First(c => c.GetTableName() == tableName);
foreach (var property in tableType.GetProperties())
{
Type type = property.ClrType;
}
现在谈到那个 Type
的字符串表示,它是任意的(类似于任何格式)并且取决于您的需要.例如,出于调试显示目的,EF Core 在内部使用 ShortDisplayName
方法.您最终可以使用它,但请注意,它使用 C# 内置类型(例如 int
而不是 Int32
)并将可为 null 的类型格式化为Nullable<{TypeName}>;"例如
Now speaking about string representation of that Type
, it is arbitrary (similar any formatting) and depends on your needs. For instance, for debug display purposes EF Core internally uses the ShortDisplayName
method. You can eventually use it, but note that it uses C# built-in types (e.g. int
instead of Int32
) and formats nullable type as "Nullable<{TypeName}>" e.g.
需要
using Microsoft.EntityFrameworkCore.Infrastructure;
然后
var tableType = _dbContext.Model.GetEntityTypes().First(c => c.GetTableName() == tableName);
foreach (var property in tableType.GetProperties())
{
var type = property.ClrType;
var typeName = type.ShortDisplayName();
}
同样,将 Type
转换为 string
是不同的,取决于这个字符串的用途.所以尽可能使用 Type
而不是 string
.GetColumnType
不同 - 它返回字符串,因为没有类似于 Type
的类来表示数据库提供程序类型.
Again, converting Type
to string
differs, and depends on what this string will be used for. So use Type
instead of string
where possible. GetColumnType
is different - it returns string because there is no class similar to Type
to represent the database provider types.
这篇关于实体框架:获取元数据 IProperty 的 DataType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!