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;
}
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.
Requires
using Microsoft.EntityFrameworkCore.Infrastructure;
and then
var tableType = _dbContext.Model.GetEntityTypes().First(c => c.GetTableName() == tableName);
foreach (var property in tableType.GetProperties())
{
var type = property.ClrType;
var typeName = type.ShortDisplayName();
}
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.