分享一个数据库匿名对象动态加载
1、用过带有Linq功能的Orm的朋友都知道匿名对象很方便,但很多项目不一定用到Orm;2、即使用了Orm,由于性能问题,很多语句需要自写,因此需要加载到对象中处理,当然你也可以用DataReader或DataTable直接处理;
3、需要对象处理就需要定义类,但很多时候一个类只有很少的地方在用,各种字段的查询组合就需要定义很多的类或算了就用DataTable吧!
4、匿名加载就派上用场了,而且可确保性能哦;
5、这个小项目由本人原创,如有雷同,纯属巧合,若有更强的也不用喷,分享一下;
先上图,再上示例码,再上源代码;
//怪上无传图
static void Main(string[] args)
{
string connectString = "data source=127.0.0.1;initial catalog=test;integrated security=True;";
using (SqlConnection conn = new SqlConnection(connectString))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
IDataReader reader;
string CmdText;
//ToList 是扩展函数,位于 Extensions 类中 实现 IDataReader 与 DataTable 扩展
//加载常规类型
CmdText = "select U.UserID from [UserRole] AS UR INNER JOIN [User] AS U ON U.UserID = UR.UserID INNER JOIN [Role] AS R ON R.RoleID = UR.RoleID";
command.CommandText = CmdText; //加载用户id
reader = command.ExecuteReader();
List<int> UserIDs = reader.ToList<int>(); //常规类型只会加载每一个字段,不区分大小名称
CmdText = "select U.UserName from [UserRole] AS UR INNER JOIN [User] AS U ON U.UserID = UR.UserID INNER JOIN [Role] AS R ON R.RoleID = UR.RoleID";
command.CommandText = CmdText; //加载用户名称
reader = command.ExecuteReader(); //加载完成必须重新执行,若想一次读取多次加载,请使用DataTable
List<string> UserNames = reader.ToList<string>();
//加载对象
CmdText = "select U.UserID,U.UserName,R.RoleID,R.RoleName from [UserRole] AS UR INNER JOIN [User] AS U ON U.UserID = UR.UserID INNER JOIN [Role] AS R ON R.RoleID = UR.RoleID";
command.CommandText = CmdText;
reader = command.ExecuteReader();
List<User> Users = reader.ToList<User>(); //用户集合
reader = command.ExecuteReader();
List<Role> Roles = reader.ToList<Role>(); //角色集合
//以上都是简单的对象,大多数人都有自己的包
//匿名对象(初始值确类型,类型要与数据库字段的类型可转换 名称一定要与字段名称相同,不区分大小写,看特性说明)
//简单
reader = command.ExecuteReader();
var u1 = reader.ToList(a => new { UserID = 0, UserName = "", RoleName = "" });
//简单,UserID 可为空(即数据库字段可为空值)
reader = command.ExecuteReader();
var u2 = reader.ToList(a => new { UserID = new Nullable<int>(), UserName = "", RoleName = "" });
//与对象混合
reader = command.ExecuteReader();
var u3 = reader.ToList(a => new { UserID = 0, UserName = "", user = new User(), role = new Role() });
//嵌套
reader = command.ExecuteReader();
var u4 = reader.ToList(a => new
{
UserID = 0,
UserName = "",
C = new
{
RoleID = 0,
RoleName = "",
user = new User(),
role = new Role(),
D = new { UserID = 0 }
}
});
}
}
源码下载:
http://download.csdn.net/detail/ycg_893/6414365 --------------------编程问答--------------------
--------------------编程问答-------------------- 反射装载属性的?有和EF的性能对比么? --------------------编程问答-------------------- 想法不错,不过感觉只能用于临时性的代码。 --------------------编程问答-------------------- 对于我个人而言 --------------------编程问答-------------------- 暂时用不上,收藏备用 --------------------编程问答-------------------- 主要是查询扩展,方便对象转换。 --------------------编程问答-------------------- 装载数据用的是Linq编译而成的委托
补充:.NET技术 , C#