/// <summary> /// 将sql查询映射为模型 /// </summary> /// <param name="modelType">模型类型</param> /// <param name="db"></param> /// <param name="sql">sql语句</param> /// <param name="parameters">参数</param> /// <returns></returns> public static IEnumerable <object> SqlQueryEx(this Database db, Type modelType, string sql, params object[] parameters) { var cmd = db.Connection.CreateCommand(); cmd.CommandText = SqlQueryExtend.GetSqlText(sql); cmd.Parameters.AddRange(SqlQueryExtend.GetParameters(cmd, parameters)); if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); } using (var reader = cmd.ExecuteReader()) { Func <Property, bool> complexFunc = item => item.Info.PropertyType != typeof(string) && item.Info.PropertyType.IsClass && item.IsVirtual == false; var properties = SqlQueryExtend.GetProperties(modelType); var complex = properties.Where(complexFunc); var primitive = properties.Where(item => !complexFunc(item)); while (reader.Read()) { var instance = Activator.CreateInstance(modelType); SqlQueryExtend.SetProperties(instance, primitive, reader); foreach (var item in complex) { SqlQueryExtend.SetComplexProperty(instance, item, reader); } yield return(instance); } } }
/// <summary> /// 设置复杂属性的值 /// </summary> /// <param name="instance"></param> /// <param name="property"></param> /// <param name="reader"></param> private static void SetComplexProperty(object instance, Property property, DbDataReader reader) { var type = property.Info.PropertyType; try { var propertyInstance = Activator.CreateInstance(type); var properties = SqlQueryExtend.GetProperties(type); SqlQueryExtend.SetProperties(propertyInstance, properties, reader); property.SetValue(instance, propertyInstance); } catch (Exception) { } }