Exemple #1
0
        /// <summary>
        /// Run time Compilered model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static List <object> ToRTModel(this IDataReader source, string name)
        {
            var res = new List <object>();
            var sb  = new StringBuilder();

            sb.AppendLine("using System;");
            sb.AppendLine("namespace RunTimeCompile");
            sb.AppendLine("{");
            sb.AppendLine("public class " + name);
            sb.AppendLine("{ ");
            for (int i = 0; i < source.FieldCount; i++)
            {
                sb.AppendLine(" public " + source.GetFieldType(i).FullName + " " + source.GetName(i) + " { get; set;} ");
            }
            sb.AppendLine("};};");

            var cdp = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters cparam = new CompilerParameters();

            cparam.ReferencedAssemblies.Add("system.dll");
            cparam.GenerateExecutable = false;
            cparam.GenerateInMemory   = true;
            var cres = cdp.CompileAssemblyFromSource(cparam, sb.ToString());

            if (cres.Errors.Count != 0)
            {
                return(res);
            }

            var oAssembly = cres.CompiledAssembly;
            var model     = oAssembly.CreateInstance("RunTimeCompile.RCO");
            var oType     = model.GetType();


            PropertyInfo[] properties = CMemoryCacher.GetValue(model.ToString()) as PropertyInfo[];
            if (properties == null)
            {
                properties = oType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                CMemoryCacher.Add(model.ToString(), properties, 1);
            }

            while (source.Read())
            {
                var i = 0;
                foreach (var prop in properties)
                {
                    var value = source.GetValue(i);
                    prop.SetValue(model, value == DBNull.Value ? null : value, null);
                    i++;
                }

                res.Add(model);
            }
            source.Close();

            return(res);
        }
Exemple #2
0
        public static T ToModel <T>(this IDataReader source) where T : new()
        {
            var model = new T();

            PropertyInfo[] properties = CMemoryCacher.GetValue(model.ToString()) as PropertyInfo[];
            if (properties == null)
            {
                properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                CMemoryCacher.Add(model.ToString(), properties, 1);
            }

            var i = 0;

            foreach (var prop in properties)
            {
                var value = source.GetValue(i);
                prop.SetValue(model, value == DBNull.Value ? null : value, null);
                i++;
            }

            return(model);
        }