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;
}
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.
Subscribe to:
Post Comments (Atom)
Can this code be used with Entity Framework? I'm not sure how to obtain DataContext because I only have an ObjectContext in EF.
ReplyDeleteSuggestions?
Thanks
Eric
Hi,
ReplyDeleteI 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