To get a table's column names you can use Entity Framework's ObjectContext API. Here’s how you could do it:
using (var db = new ProjectNameContext())
{
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
var entityType = objectContext.CreateObjectSet<User>().EntitySet.Elements[0].TypeUsage.EdmType as EntityType;
if (entityType != null)
colNames = entityType.Properties.Select(p => p.Name).ToArray();
}
In this snippet, we're using CreateObjectSet
to create an ObjectSet of a user-defined type from our context. We then access the Elements collection on that EntitySet, which contains metadata about all types present in it. Here we are taking the first item and casting its EdmType to an EntityType - if we were dealing with more complex sets (like association sets), we'd need a bit different code.
Next, we can get a list of column names by iterating over properties within our entity type in entityType.Properties
. These represent the columns present on this table in your database and each Property object has its name which is used for getting column name.
Finally, calling ToArray() will return an array containing all property names from Entity Type.
Note: Replace 'User' with the actual entity type you want to fetch column information for.
Also note that this code only works when EF generates a .ssdl(Stored Schema Definition Language) and/or .sst(Store Schema Tookit) for your context based on database, if it does not then it won't be able to access metadata about properties or entity. If you're using model-first or Database First approach with EF 5 then ObjectContext API would still work as same.