如何解决如何将集合转换为数据表
能帮我解决这个问题吗?
而且是我想影响对象类型集合Adhérent到数据表
代码:
BiblioEntities b = new BiblioEntities();
var ad = b.Adhérent.SqlQuery(@"select * from Adhérent ").ToList();
DataTable dt = (DataTable)ad;
错误:
不可能的转换类型'
System.Collections.Generic.List<Biblio.Adhérent>
'和'System.Data.DataTable
'
解决方法
我在实体框架模型中使用了以下扩展名,它将适用于任何类型的集合:
public static System.Data.DataTable ToDataTable<T>(this IEnumerable<T> source)
{
var table = new System.Data.DataTable(typeof(T).Name);
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var prop in props)
{
table.Columns.Add(prop.Name,Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (var item in source)
{
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item,null);
}
table.Rows.Add(values);
}
return table;
}
并将其应用于示例代码将是这样的:
var dt= new BiblioEntities().Adhérent.SqlQuery(@"select * from Adhérent ").ToDataTable();
,
这是另一种实现方式
public static class DataTableConverter
{
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name,Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
}
要添加到您的代码中,请执行以下操作:
var dt = DataTableConverter.ToDataTable(ad);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。