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 would like to get "Column Name, Column's Value" in an tuple array list with entity framework.

I have this:

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

to get 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 done it? Thanks a lot...

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

Accepted Answer

A column on its own isn't enough; you'll need to read the column values from a specific entity.

Once you have an entity, you can use the DbContext.Entry method to get the DbEntityEntry instance for that entity. The CurrentValues property will then give you access to the current property values for that entity.

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