4

Using Entity Framework 5, database first.

Is it possible (at run time) to get the data type of the database column that an entity's property represents? The .net type would also work fine if that's 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?
   }
}

2 Answers 2

3

To get the data type of the particular column of the table:

[Assume: Entity prop class name: Vendors and column name ="VendorID"]

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

To get all columns names and type of the columns dynamically:

[Param : 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
                       };
Sign up to request clarification or add additional context in comments.

2 Comments

I got an error at EntitySet. "doesn't contain definition for EntitySet"
This is really useful because it allows you to get things like EntityProperty.MaxLength and EdmProperty.IsUnicode without having to try to duplicate functionality already inside of EntityFramework.
1

Use reflection on the entity to get the property info.

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

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.