How to get Column name and corresponding Database Type from DbContext in Entity Framework Core
Closed this issue · 1 comments
HamedFathi commented
Suppose I have this table:
How can I get ColumnName and Database Type from DbContext in Entity Framework Core.
Tips
-
The column with name clg# converted to clg1 by EF Core Scaffold tool so I need real column name not current EF name.
-
I need database type not clrType, of course the must be cross platform. Maybe I will change the database so the method must be work too.
Desired result:
< D.clg#,int >
< D.clgname,nvarchar(50) >
< D.city,nvarchar(50) >
< D.pname,nvarchar(50) >
Can anyone provide a solution ?
HamedFathi commented
Solution stackoverflow :
public class DbColumnInfo
{
public string Name;
public string Type;
}
public static class RelationalDbHelpers
{
public static IEnumerable<DbColumnInfo> GetDbColums(this DbContext dbContext, Type clrEntityType)
{
var dbServices = dbContext.GetService<IDbContextServices>();
var relationalDbServices = dbServices.DatabaseProviderServices as IRelationalDatabaseProviderServices;
var annotationProvider = relationalDbServices.AnnotationProvider;
var typeMapper = relationalDbServices.TypeMapper;
var entityType = dbContext.Model.FindEntityType(clrEntityType);
// Not needed here, just an example
var tableMap = annotationProvider.For(entityType);
var tableName = tableMap.TableName;
var tableSchema = tableMap.Schema;
return from property in entityType.GetProperties()
let columnMap = annotationProvider.For(property)
let columnTypeMap = typeMapper.FindMapping(property)
select new DbColumnInfo
{
Name = columnMap.ColumnName,
Type = columnTypeMap.StoreType
};
}
}