Entity Framework - getting a table's column names as a string array

user982119 picture user982119 · Oct 31, 2013 · Viewed 36.1k times · Source

If I'm using EF 5 and Database first to generate a .edmx model of my database, how do I get a list of an entity's columns?

using (var db = new ProjectNameContext())
{
    // string[] colNames = db.Users.
}

What I'm looking for is colNames[0] == "Id", colNames[1] == "FirstName", etc.

Answer

dav_i picture dav_i · Oct 31, 2013

How about:

var names = typeof(User).GetProperties()
                        .Select(property => property.Name)
                        .ToArray();

Of course, this can be used for any type, not just an EF table.