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

后端 未结 2 852
日久生厌
日久生厌 2020-12-28 15:36

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 ProjectNameC         


        
相关标签:
2条回答
  • 2020-12-28 15:54
    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
    
    0 讨论(0)
  • 2020-12-28 16:09

    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.

    0 讨论(0)
提交回复
热议问题