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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
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.
@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?
@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.
This looks like the property name, is that the same thing as the column name?
|
12
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

3 Comments

Could you please clarify, what is the difference between the two and what the latter does differently? Is the result the same?
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.
Hi, I think the answer should be updated : stackoverflow.com/a/42467710

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.