把Linq查询返回的var类型的数据 转换为DataTable EF连接查询
问题:我要获得一个角色下对应的所有用户,需要两表连接查询,虽然返回的只有用户数据,但是我想到若是返回的不只是用户数据,而还要加上角色信息,那么我返回什么类型呢,返回var吗,这样不行。
于是我网上找找是否能返回DataTable呢,这样我不用创建中间类了。然后就找到下面的代码:这是别人写的,高手。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace Common
{
public static class DataSetLinqOperators
{
public static DataTable CopyToDataTable<T>(this IEnumerable<T> source)
{
return new ObjectShredder<T>().Shred(source, null, null);
} public static DataTable CopyToDataTable<T>(this IEnumerable<T> source,DataTable table, LoadOption? options)
{
return new ObjectShredder<T>().Shred(source, table, options);
} } public class ObjectShredder<T>
{
private FieldInfo[] _fi;
private PropertyInfo[] _pi;
private Dictionary<string, int> _ordinalMap;
private Type _type; public ObjectShredder()
{
_type = typeof(T);
_fi = _type.GetFields();
_pi = _type.GetProperties();
_ordinalMap = new Dictionary<string, int>();
} public DataTable Shred(IEnumerable<T> source, DataTable table, LoadOption? options)
{
if (typeof(T).IsPrimitive)
{
return ShredPrimitive(source, table, options);
} if (table == null)
{
table = new DataTable(typeof(T).Name);
} // now see if need to extend datatable base on the type T + build ordinal map
table = ExtendTable(table, typeof(T)); table.BeginLoadData();
using (IEnumerator<T> e = source.GetEnumerator())
{
while (e.MoveNext())
{
if (options != null)
{
table.LoadDataRow(ShredObject(table, e.Current), (LoadOption)options);
}
else
{
table.LoadDataRow(ShredObject(table, e.Current), true);
}
}
}
table.EndLoadData();
return table;
} public DataTable ShredPrimitive(IEnumerable<T> source, DataTable table, LoadOption? options)
{
if (table == null)
{
table = new DataTable(typeof(T).Name);
} if (!table.Columns.Contains("Value"))
{
table.Columns.Add("Value", typeof(T));
} table.BeginLoadData();
using (IEnumerator<T> e = source.GetEnumerator())
{
Object[] values = new object[table.Columns.Count];
while (e.MoveNext())
{
values[table.Columns["Value"].Ordinal] = e.Current; if (options != null)
{
table.LoadDataRow(values, (LoadOption)options);
}
else
{
table.LoadDataRow(values, true);
}
}
}
table.EndLoadData();
return table;
} public DataTable ExtendTable(DataTable table, Type type)
{
// value is type derived from T, may need to extend table.
foreach (FieldInfo f in type.GetFields())
{
if (!_ordinalMap.ContainsKey(f.Name))
{
DataColumn dc = table.Columns.Contains(f.Name) ? table.Columns[f.Name]
: table.Columns.Add(f.Name, f.FieldType);
_ordinalMap.Add(f.Name, dc.Ordinal);
}
}
foreach (PropertyInfo p in type.GetProperties())
{
if (!_ordinalMap.ContainsKey(p.Name))
{
DataColumn dc = table.Columns.Contains(p.Name) ? table.Columns[p.Name]
: table.Columns.Add(p.Name, p.PropertyType);
_ordinalMap.Add(p.Name, dc.Ordinal);
}
}
return table;
} public object[] ShredObject(DataTable table, T instance)
{ FieldInfo[] fi = _fi;
PropertyInfo[] pi = _pi; if (instance.GetType() != typeof(T))
{
ExtendTable(table, instance.GetType());
fi = instance.GetType().GetFields();
pi = instance.GetType().GetProperties();
} Object[] values = new object[table.Columns.Count];
foreach (FieldInfo f in fi)
{
values[_ordinalMap[f.Name]] = f.GetValue(instance);
} foreach (PropertyInfo p in pi)
{
values[_ordinalMap[p.Name]] = p.GetValue(instance, null);
}
return values;
}
}
}
来源:http://www.cnblogs.com/jaxu/archive/2011/08/02/2125055.html
Jaxu的博客写挺好的,都可以看看。
不过我最后没有用这个方法,我新建了一个中间类,来形成List返回:
/// <summary>
/// 根据RoleID获得该角色下的用户成员
/// </summary>
/// <param name="rid"></param>
/// <returns></returns>
public List<S_ROLE_USER_Query_Dto> GetRoleUser(int rid, string name)
{
IQueryable<S_ROLE_USER_Query_Dto> result = from ru in this.Context.Set<Domain.S_ROLE_USER>()
join u in this.Context.Set<Domain.S_USER>()
on new { ru.U_ID }
equals new { u.U_ID }
where (ru.R_ID == rid && (string.IsNullOrEmpty(name) ? true : (u.U_NAME.Contains(name) || u.U_REALNAME.Contains(name))))
select new S_ROLE_USER_Query_Dto
{
U_ID = ru.U_ID,
U_NAME = u.U_NAME,
U_REALNAME = u.U_REALNAME,
U_EMAIL = u.U_EMAIL,
U_MOBILE = u.U_MOBILE,
U_TEL = u.U_TEL,
R_ID = ru.R_ID
};
return result.ToList();
}
把Linq查询返回的var类型的数据 转换为DataTable EF连接查询的更多相关文章
- linq之将IEnumerable<T>类型的集合转换为DataTable类型 (转载)
在考虑将表格数据导出成excel的时候,网上搜的时候找到一个特别合适的公共方法,可以将query查询出来的集合转换为datatable 需引用using System.Reflection; publ ...
- 使用js处理后台返回的Date类型的数据
从后台返回的日期类型的数据,如果直接在前端进行显示的话,显示的就是一个从 1970-01-01 00:00:00到现在所经过的毫秒数,而在大多数业务中都不可能显示这个毫秒数,大多数都是显示一个正常的日 ...
- 【数据传输 2】批量导入的前奏:将Excel表中的数据转换为DataTable类型
导读:我们知道,在数据库中,数据集DataSet是由多张DataTable表组成.所以,如果我们需要将数据从外部导入到数据库中,那么要做的很重要的一步是将这些数据转换为数据库可以接受的结构.今天在用S ...
- C# Winform中执行post操作并获取返回的XML类型的数据
/// <summary> /// 返回指定日期的订单数据 /// </summary> /// <param name="StartDate"> ...
- 记录一个EF连接查询的异常:the entity or complex type 'x' cannot be constructed in a linq to entities query
问题解决连接:https://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a-linq-to-ent ...
- 使用 DML语句,对 “锦图网” 数据进行操作,连接查询(内连接,左外连接,右外连接,全连接)
查看本章节 查看作业目录 需求说明: 对 "锦图网" 数据进行操作: 统计每一种线路类型的线路数量.最高线路价格.最低线路价格和平均线路价格,要求按照线路数量和平均线路价格升序显示 ...
- 【C#】将数据库读出的数据转换为DataTable类型集合
return View(ConverDataReaderToDataTable(reader)); // 静态方法public static DataTable ConverDataReaderToD ...
- mysql第四篇:数据操作之多表查询
mysql第四篇:数据操作之多表查询 一.多表联合查询 #创建部门 CREATE TABLE IF NOT EXISTS dept ( did int not null auto_increment ...
- HQL查询——查询返回对象类型分析
关于HQL查询,我们可以结合hibernate的API文档,重点围绕org.hibernate.Query接口,分析其方法,此接口的实例对象是通过通过session.对象的creatQuery(Str ...
随机推荐
- xgCalendar在ASP.NET中的使用
1.将wdCalendar文件夹考入项目中 2.在页面中添加引用,见3中head标签中定义 3.配置xgCalendar,两段代码放在一起就是完整的页面 body> <div> &l ...
- 爬虫框架之Scrapy——爬取某招聘信息网站
案例1:爬取内容存储为一个文件 1.建立项目 C:\pythonStudy\ScrapyProject>scrapy startproject tenCent New Scrapy projec ...
- SQL查询日期:
SQL查询日期: 今天的所有数据:select * from 表名 where DateDiff(dd,datetime类型字段,getdate())=0 昨天的所有数据:select * from ...
- unity3d之Editor的Assembly-CSharp.dll文件路径
在Editor中与自己project中使用的Mono与Managed文件夹路径区别: Editor中:在unity安装路径[AppDir]下: 自己project中:在project的路径下,由bui ...
- 【Linux_Unix系统编程】Chapter4 文件IO
Chapter4 文件IO 4.1 概述 文件描述符 == Windows的句柄 标准文件描述符: 0 标准输入 STDIN_FILENO stdin 1 标准输出 STDOUT_FILENO std ...
- 查看shell环境下,网络是否连通-curl/ping
检查网络是否可用 curl www.baidu.com <!--STATUS OK--><html>...</html> ping www.baidu.com注意: ...
- 17.scrapy框架简例使用
目标:创建scrapy项目 创建一个spider来抓取站点和处理数据 通过命令行将抓取内容导出 1.创建项目 scrapy startproject tutorial 2.创建spider cd tu ...
- 装机 win7 64 IE11
英文版win7,更改语言包 英文版 http://windows.microsoft.com/en-us/internet-explorer/download-ie 中文版 http://window ...
- 去除android手机浏览器中, 按住链接出现border的情况
body{ -moz-user-select:none; -webkit-user-select:none; -webkit-tap-highlight-color:transparent; }
- 基于OpenGL编写一个简易的2D渲染框架-02 搭建OpenGL环境
由于没有使用GLFW库,接下来得费一番功夫. 阅读这篇文章前请看一下这个网页:https://learnopengl-cn.github.io/01%20Getting%20started/02%20 ...