实体框架:获取元数据IProperty的数据类型 [英] Entity Framework: Get the DataType of Metadata IProperty
问题描述
如何在Entity Framework Core中找到Metadata.IProperty的数据类型?
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+ 阴影属性,它们没有关联的 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在内部使用
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的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!