How to get column names and and their values to array tuple list with Entity Framework

c# c#-4.0 c#-5.0 entity-framework entity-framework-6

Question

I need "Column Name, Column's Value" in a list of tuples with the indexes frame for entities.

I own this

var colNames = typeof(tbl_ObisSchema).GetProperties().Select(a => a.Name).ToList();

for a list of all column names

 using (var dbContext = new db_ReadyEngine_MSSQL())
{
 var colNames = typeof(tbl_ObisSchema).GetProperties().Select(a => a.Name).ToList();

 List<Tuple<string, string>> list = new List<Tuple<string, string>>();
 list.Add(Tuple.Create(ColumnName, ColumnValue));

}

How did it go? Many thanks.

1
1
3/5/2014 4:28:25 PM

Accepted Answer

You must read the column values from a particular entity because a column by itself is insufficient.

Using the DbContext.Entry method, you can obtain the DbEntityEntry instance of an entity once you have it. You can then retrieve the most recent property values for that object by using the CurrentValues property.

using (var dbContext = new db_ReadyEngine_MSSQL())
{
    var entity = dbContext.Set<tbl_ObisSchema>().Find(thePrimaryKeyToFind);
    if (entity == null) throw new InvalidOperationException("Record not found");

    var entry = dbContext.Entry(entity);
    var currentPropertyValues = entry.CurrentValues;

    List<Tuple<string, object>> list = currentPropertyValues.PropertyNames
        .Select(name => Tuple.Create(name, currentPropertyValues[name]))
        .ToList();

    // Do something with the list...
}
2
3/5/2014 5:21:27 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow