Get column data type from Entity Framework Entity

First use the Entity Framework 5 database.

Is it possible (at run time) to get the data type of a database column, which is an object property? The .net type will also work fine if it is easier.

IEnumerable<DbEntityEntry> entities = context.ChangeTracker.Entries() .Where( e => e.State == EntityState.Added || e.State == EntityState.Modified); foreach (DbEntityEntry entity in entities) { foreach (string propertyName in entity.CurrentValues.PropertyNames) { //so I know the entity and the property name. Can I get the data type? } } 
+1
source share
2 answers

Use object reflection to get information about properties.

 foreach (DbEntityEntry entity in entities) { foreach (string propertyName in entity.CurrentValues.PropertyNames) { var propertyInfo = entity.Entity.GetType().GetProperty(propertyName); var propertyType = propertyInfo.PropertyType; } } 
+1
source

To get the data type for a specific column in a table:

[Assume: Entity support class name: providers and column name = "VendorID"]

 string columnTypName = (context.Vendors.EntitySet.ElementType.Members["VendorID"].TypeUsage.EdmType).Name; 

To dynamically create column names and column types :

[Parameter: tableName]

 var columns = from meta in ctx.MetadataWorkspace.GetItems(DataSpace.CSpace) .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType) from p in (meta as EntityType).Properties .Where(p => p.DeclaringType.Name == tableName) select new { colName = p.Name, colType = p.TypeUsage.EdmType.Name }; 
+2
source

Source: https://habr.com/ru/post/989244/


All Articles