Dapper 嵌套对象查询

我有这样一个一对一关系的表结构:User->UserInfo

User:

 /// <summary>
	/// 用户
	/// </summary>
	[Serializable]
	public partial class SysUser
	{
		public SysUser()
		{}
		#region Model
		/// <summary>
		/// 用户编号
		/// </summary>
		public string SysId { get; set; }

		/// <summary>
		/// 用户名
		/// </summary>
		public string UserName { get; set; }

		/// <summary>
		/// 密码
		/// </summary>
		public string UserPwd { get; set; }

		/// <summary>
		/// 创建时间
		/// </summary>
		public DateTime? CreateTime { get; set; }

		/// <summary>
		/// 最后一次登录时间
		/// </summary>
		public DateTime? LastLogin { get; set; }

		/// <summary>
		/// 该条记录的操作情况,用于记录最后一次谁在什么时候创建、修改了该记录
		/// </summary>
		public string RecordStatus { get; set; }

        /// <summary>
        /// 用户的详细信息
        /// </summary>
        public SysUserInfo UserInfo { get; set; }
         
		#endregion Model

        public IEnumerable<SysRole> Roles { get; set; }
	}

 

UserInfo:

/// <summary>
	/// 用户信息
	/// </summary>
	[Serializable]
	public partial class SysUserInfo
	{
		public SysUserInfo()
		{}
		#region Model
		/// <summary>
		/// 用户编号
		/// </summary>
		public string SysId { get; set; }

		/// <summary>
		/// 真实名字
		/// </summary>
		public string RealName { get; set; }

		/// <summary>
		/// 职位
		/// </summary>
		public string Title { get; set; }

		/// <summary>
		/// 性别
		/// </summary>
		public bool Sex { get; set; }

		/// <summary>
		/// 手机
		/// </summary>
		public string Phone { get; set; }

		/// <summary>
		/// 传真
		/// </summary>
		public string Fax { get; set; }

		/// <summary>
		/// 邮箱
		/// </summary>
		public string Email { get; set; }

		/// <summary>
		/// qq
		/// </summary>
		public string QQ { get; set; }

		/// <summary>
		/// 地址
		/// </summary>
		public string Address { get; set; }

		#endregion Model

	}

 

 

查询的具体Sql:

select u.CreateTime,u.LastLogin,u.RecordStatus,u.SysId,u.UserName,u.UserPwd,ui.SysId,
	   ui.Address,ui.Email,ui.Fax,ui.Phone,ui.QQ,ui.RealName,ui.Sex,ui.Title
from Sys_User u inner join Sys_UserInfo ui on u.SysId=ui.SysId inner join Sys_UserRole ur on 
u.SysId=ur.UserId inner join Sys_Role r on ur.RoleId = r.SysId 

 

要想把UserInfo的数据填充到User中,需要用下面的方式实现:

connection.Query<SysUser, SysUserInfo, SysUser>(
                    Constant.ProcGetList,
                    (u, ui) =>
                        {
                            u.UserInfo = ui;
                            return u;
                        },
                        p,splitOn:"SysId",
                    commandType: CommandType.StoredProcedure);

 

 

此处要注意的就是splitOn,他其它是分割子对象的属性。

posted @ 2013-09-12 17:56  吉桂昕  阅读(1930)  评论(0编辑  收藏  举报