Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 383
notAnonymousAnymore Avatar asked Oct 31 '13 10:10

notAnonymousAnymore


2 Answers

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.

like image 120
dav_i Avatar answered Nov 15 '22 01:11

dav_i


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
like image 10
Mark Macneil Bikeio Avatar answered Nov 15 '22 01:11

Mark Macneil Bikeio