Suppose I have this table:
How can I get the column name and database datatype 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 work too.
Desired result:
<D.clg#, int>
<D.clgname, nvarchar(50)>
<D.city, nvarchar(50)>
<D.pname, nvarchar(50)>
Can anyone provide a solution ?
Update: Starting with EF Core 2.0, the things have changed, so the original answer does not apply anymore. Now EF Core builds separate model for each database type, so the code is much simpler and uses directly the
Relational()
extensions:Original answer (EF Core 1.x):
Getting the access to the associated metadata is much easier in EF Core compared to EF - you start from
DbContext.Model
property to getIModel
, useGetEntityTypes
orFindEntityType
to getIEntityType
, thenGetProperties
orFindProperty
to getIProperty
etc.However the problem is that EF Core allows you to use different setting fro different target database. In order to get the attributes corresponding to the current database used by the context, you need to get access to the
IRelationalDatabaseProviderServices
and useAnnotationProvider
andTypeMapper
properties to get the information needed.Here is an example: