25

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.

notAnonymousAnymore
  • 2,637
  • 9
  • 49
  • 74

2 Answers2

47

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.

dav_i
  • 27,509
  • 17
  • 104
  • 136
  • 36
    This is not accurate. Properties can be mapped to column names that are not the same as the property name via specific configurations but also via conventions. – George Mauer Feb 24 '16 at 15:51
  • 1
    Adding to what @GeorgeMauer wrote: EF allows for props suffixed with "Id" to automatically map to an object of the same name w/o the Id suffix, which is the actual column name. Thus if you had "object Name" and "int NameId" there would be a "Name" column of type int, but no NameId column. – dlchambers Mar 15 '16 at 18:50
  • 1
    @davi_i how do i iterate through a list of tables ad get the column names of the tables. I want to set the table name dynamically instead of saying typeof(User). Can that be done? – Gayanee Wijayasekara Jan 15 '17 at 17:36
  • @GayaneeWijayasekara Hey, I'd ask a new question. That way more people will be able to see your question to answer it and it may help someone else in the future. – dav_i Jan 15 '17 at 19:07
  • 1
    This looks like the property name, is that the same thing as the column name? – Demodave Mar 21 '19 at 18:34
  • @GeorgeMauer I have answered below for the column names different. – Rahul Uttarkar Jul 11 '19 at 07:22
11
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
Rahul Uttarkar
  • 3,367
  • 3
  • 35
  • 40
  • Could you please clarify, what is the difference between the two and what the latter does differently? Is the result the same? – André Reichelt Aug 22 '19 at 08:37
  • 5
    The latter will give you the actual name of the column while the first will only give you the name of the property. So if property `foo` is mapped to column `bar` then the latter will give you `"bar"`. So the latter is the actual answer to the question, the accepted answer isn't. It requires EF Core 2.x though. – Oskar Sep 13 '19 at 14:15