Sunday, July 10, 2011

Linq to Sql/Entities Table values using Reflection

The following function takes input table name, data field column name and data value column name and returns list of ListItem so developer can use this list in dropdown and other list control. the following function uses reflection to access table and column for values.

 public List<ListItem> GetListOfValue(string dataFieldName, string dataFieldValue, string tableName)  
{
List<ListItem> listItemList = new List<ListItem>();
ListItem listItem = null;
MetaTable table = _dataContext.Mapping.GetTables().Where(t => t.TableName.ToUpper().Equals("DBO." + tableName.ToUpper())).FirstOrDefault();
if (table == null)
throw new NullReferenceException("table");
ITable iTable = _dataContext.GetTable(table.RowType.Type);
if (iTable == null)
throw new NullReferenceException("iTable");
List<object> objectList = iTable.OfType<object>().ToList();
foreach (object obj in objectList)
{
listItem = new ListItem();
foreach (PropertyInfo property in obj.GetType().GetProperties())
{
if (property.Name.ToUpper().Equals(dataFieldName.ToUpper()))
{
listItem.Text = property.GetValue(obj, null).ToString();
}
if (property.Name.ToUpper().Equals(dataFieldValue.ToUpper()))
{
listItem.Value = property.GetValue(obj, null).ToString();
}
}
listItemList.Add(listItem);
}
return listItemList;
}

2 comments:

  1. Can this code be used with Entity Framework? I'm not sure how to obtain DataContext because I only have an ObjectContext in EF.

    Suggestions?
    Thanks
    Eric

    ReplyDelete
  2. Hi,

    I dont have any complete solution for this but refer to these sites for more information

    http://pastebin.com/kjXUKBNS
    http://stackoverflow.com/questions/6156538/entityframework-get-object-by-id

    http://stackoverflow.com/questions/8112531/entity-framework-reflecting-on-foreign-keys-and-relationships-associations

    Hope this helps and you would find your solution.

    Thanks

    ReplyDelete