Sunday, January 22, 2012

ObjectContext List of Fields/Tables

I've been digging around trying to find a way to dynamically pull a list of tables and their associated fields from an ObjectContext and I think I just found a solution, courtesy again of StackOverflow. Here's what I came up with to solve my particular problem, not my best work, but it'll do. I've set it up to be added to a partial class of an existing ObjectContext, so it can be called via "context.GetTableList()" or "context.GetFieldList("TableName")".
public List<string> GetTableList()
{
    var r = new List<string>();
    var query = from meta in this.MetadataWorkspace.GetItems(DataSpace.CSpace)
                .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                let properties = meta is EntityType ? (meta as EntityType).Properties : null
                select new { TableName = (meta as EntityType).Name };
    query.ToList().ForEach(c => r.Add(c.TableName));
    return r;
}

public List<string> GetFieldList(string table)
{
    var r = new List<string>();
    var query = from meta in this.MetadataWorkspace.GetItems(DataSpace.CSpace)
                .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
                let properties = meta is EntityType ? (meta as EntityType).Properties : null
                where (meta as EntityType).Name == table
                from p in properties
                select new
                {
                    FieldName = p.Name,
                    DbType = p.TypeUsage.EdmType.Name
                };
    query.ToList().ForEach(c => r.Add(c.FieldName));
    return r;
}

Source

No comments:

Post a Comment