Entity Framework - how do I get the columns?

后端 未结 7 1531
后悔当初
后悔当初 2020-12-01 14:25

I wish to get a list of columns names, types and whether the column is a PK of a table object in Entity Framework.

How do I do this in C# (4.0) (ideally generically)

相关标签:
7条回答
  • 2020-12-01 15:01

    If anyone is still looking, Here's how I did it. This is an extension method for the DBContext that takes a type and returns physical column names and their properties.

    This utilizes object context to get physical columns list, then uses the "PreferredName" metadata property to map each column it its property.

    Since it uses object context, it initiates a database connection, so the first run will be slow depending on the complexity of the context.

    public static IDictionary<String, PropertyInfo> GetTableColumns(this DbContext ctx, Type entityType)
    {
        ObjectContext octx = (ctx as IObjectContextAdapter).ObjectContext;
        EntityType storageEntityType = octx.MetadataWorkspace.GetItems(DataSpace.SSpace)
            .Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntityType).OfType<EntityType>()
            .Single(x => x.Name == entityType.Name);
    
        var columnNames = storageEntityType.Properties.ToDictionary(x => x.Name,
            y => y.MetadataProperties.FirstOrDefault(x => x.Name == "PreferredName")?.Value as string ?? y.Name);
    
        return storageEntityType.Properties.Select((elm, index) =>
                new {elm.Name, Property = entityType.GetProperty(columnNames[elm.Name])})
            .ToDictionary(x => x.Name, x => x.Property);
    }
    

    To use it, just create a helper static class, and add above function; then it's as simple as calling

    var tabCols = context.GetTableColumns(typeof(EntityType));
    
    0 讨论(0)
提交回复
热议问题