notAnonymousAnymore
notAnonymousAnymore

Reputation: 2687

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

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.

Upvotes: 25

Views: 49872

Answers (2)

Rahul Uttarkar
Rahul Uttarkar

Reputation: 3635

var res = typeof(TableName).GetProperties()
                        .Select(property => property.Name)
                        .ToArray();

OR

var res = dbContext.Model.FindEntityType(typeof(TableName))
                           .GetProperties().Select(x => x.Relational().ColumnName)
                           .ToList();

var index = 0;    
var propertyInfo = res[index].PropertyInfo;

var columnName = res[index].Relational().ColumnName;
var propertyName = propertyInfo.Name;
var propertyValue = propertyInfo.GetValue(sourceObject); // NEED OBJECT TO GET VALUE

Upvotes: 12

dav_i
dav_i

Reputation: 28107

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.

Upvotes: 46

Related Questions