Created
May 28, 2013 23:07
-
-
Save bhameyie/5666836 to your computer and use it in GitHub Desktop.
dynamic table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DynamicTable : DynamicObject | |
{ | |
private readonly DataTable m_dataTable; | |
public DynamicTable(DataTable dataTable) | |
{ | |
m_dataTable = dataTable; | |
} | |
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) | |
{ | |
if (indexes.Length != 1) | |
{ | |
throw new ArgumentException("Only accepts 1 index"); | |
} | |
var i = (int)indexes[0]; | |
if (i > -1 && i < Count) | |
{ | |
result = new DynamicRow(m_dataTable.Rows[i]); | |
return true; | |
} | |
throw new IndexOutOfRangeException(); | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
var memberName = binder.Name; | |
if (memberName.Equals("Count")) | |
{ | |
result = Count; | |
return true; | |
} | |
result = null; | |
return false; | |
} | |
private int Count | |
{ | |
get { return m_dataTable.Rows.Count; } | |
} | |
public class DynamicRow : DynamicObject | |
{ | |
private readonly DataRow m_row; | |
public DynamicRow(DataRow row) | |
{ | |
m_row = row; | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
var columnName = binder.Name; | |
try | |
{ | |
result = m_row[columnName]; | |
return true; | |
} | |
catch (Exception) | |
{ | |
result = null; | |
return false; | |
} | |
} | |
//warning: the row MUST have all of the properties defined on the entity. | |
public T Convert<T>() where T : new() | |
{ | |
var entity = new T(); | |
var propertyInfos = entity.GetType().GetProperties(); | |
foreach (var propertyInfo in propertyInfos) | |
{ | |
propertyInfo.SetValue(entity, m_row[propertyInfo.Name], null); | |
} | |
return entity; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment