/// <summary> /// 数据填充 /// </summary> /// <param name="reader">源IDataReader</param> /// <typeparam name="TEntity">实体类</typeparam> public static TEntity ToEntity <TEntity>(this IDataReader reader) where TEntity : class, new() { var map = SetMapCacheManger.Cache(typeof(TEntity)); var t = (TEntity)Activator.CreateInstance(typeof(TEntity)); var isHaveValue = false; if (reader.Read()) { //赋值字段 foreach (var kic in map.MapList) { if (HaveName(reader, kic.Value.Field.Name)) { if (!kic.Key.CanWrite) { continue; } var oVal = ConvertHelper.ConvertType(reader[kic.Value.Field.Name], kic.Key.PropertyType); PropertySetCacheManger.Cache(kic.Key, t, oVal); isHaveValue = true; } } } reader.Close(); return(isHaveValue ? t : null); }
/// <summary> /// IDataReader转换为实体类 /// </summary> /// <param name="reader">源IDataReader</param> /// <typeparam name="TEntity">实体类</typeparam> public static List <TEntity> ToList <TEntity>(this IDataReader reader) where TEntity : class, new() { var list = new List <TEntity>(); var map = SetMapCacheManger.Cache(typeof(TEntity)); while (reader.Read()) { var t = (TEntity)Activator.CreateInstance(typeof(TEntity)); //赋值字段 foreach (var kic in map.MapList) { if (HaveName(reader, kic.Value.Field.Name)) { if (!kic.Key.CanWrite) { continue; } var oVal = ConvertHelper.ConvertType(reader[kic.Value.Field.Name], kic.Key.PropertyType); PropertySetCacheManger.Cache(kic.Key, t, oVal); } } list.Add(t); } reader.Close(); return(list); }
/// <summary> /// DataTable转换为实体类 /// </summary> /// <param name="dt">源DataTable</param> /// <typeparam name="TEntity">实体类</typeparam> public static List <TEntity> ToList <TEntity>(this DataTable dt) where TEntity : class, new() { var list = new List <TEntity>(); var map = SetMapCacheManger.Cache(typeof(TEntity)); foreach (DataRow dr in dt.Rows) { // 赋值字段 var t = new TEntity(); foreach (var kic in map.MapList) { if (!kic.Key.CanWrite) { continue; } var filedName = kic.Value.Field.IsFun ? kic.Key.Name : kic.Value.Field.Name; if (dr.Table.Columns.Contains(filedName)) { var oVal = ConvertHelper.ConvertType(dr[filedName], kic.Key.PropertyType); PropertySetCacheManger.Cache(kic.Key, t, oVal); } } list.Add(t); } return(list); }
/// <summary> /// 将DataRow转成实体类 /// </summary> /// <typeparam name="TEntity">实体类</typeparam> /// <param name="dr">源DataRow</param> public static TEntity ToInfo <TEntity>(DataRow dr) where TEntity : class, new() { var map = SetMapCacheManger.Cache(typeof(TEntity)); var t = new TEntity(); //赋值字段 foreach (var kic in map.MapList) { if (!kic.Key.CanWrite) { continue; } var filedName = kic.Value.Field.IsFun ? kic.Key.Name : kic.Value.Field.Name; if (dr.Table.Columns.Contains(filedName)) { var oVal = dr[filedName].ConvertType(kic.Key.PropertyType); if (oVal == null) { continue; } PropertySetCacheManger.Cache(kic.Key, t, oVal); } } return(t); }
/// <summary> /// 将集合类转换成DataTable /// </summary> /// <param name="lst">集合</param> /// <returns></returns> public static DataTable ToTable <TEntity>(this List <TEntity> lst) where TEntity : class { var dt = new DataTable(); if (lst.Count == 0) { return(dt); } var map = SetMapCacheManger.Cache(typeof(TEntity)); var lstFields = map.MapList.Where(o => o.Value.Field.IsMap).OrderBy(o => o.Value.Field.FieldIndex).ToList(); // 添加DataTable列 foreach (var field in lstFields) { // 对 List 类型处理 var type = field.Key.PropertyType.GetNullableArguments(); if (type.IsEnum) { type = typeof(int); } var col = new DataColumn(field.Value.Field.Name, type) { AutoIncrement = field.Value.Field.IsDbGenerated }; dt.Columns.Add(col); } foreach (var info in lst) { var dr = dt.NewRow(); foreach (var field in lstFields) { var value = ConvertHelper.GetValue(info, field.Key.Name, (object)null); var type = field.Key.PropertyType.GetNullableArguments(); // 枚举特殊处理 if (type.IsEnum) { value = (int)(value ?? 0); } dr[field.Value.Field.Name] = (value == null && !type.IsClass) || field.Value.Field.IsDbGenerated ? 0 : value; } dt.Rows.Add(dr); } return(dt); }
/// <summary> /// 将DataRow转成实体类 /// </summary> /// <typeparam name="TEntity">实体类</typeparam> /// <param name="dr">源DataRow</param> public static TEntity ToInfo <TEntity>(this DataRow dr) where TEntity : class, new() { var map = SetMapCacheManger.Cache(typeof(TEntity)); var t = (TEntity)Activator.CreateInstance(typeof(TEntity)); //赋值字段 foreach (var kic in map.MapList) { if (dr.Table.Columns.Contains(kic.Value.Field.Name)) { if (!kic.Key.CanWrite) { continue; } PropertySetCacheManger.Cache(kic.Key, t, dr[kic.Value.Field.Name].ConvertType(kic.Key.PropertyType)); } } return(t ?? new TEntity()); }
/// <summary> /// 检测实体类值状况 /// </summary> /// <param name="dicError">返回错误消息,key:属性名称;vakue:错误消息</param> /// <param name="entity">要检测的实体</param> public static bool Check <TEntity>(this TEntity entity, out Dictionary <string, List <string> > dicError) where TEntity : IVerification { dicError = new Dictionary <string, List <string> >(); var map = SetMapCacheManger.Cache(typeof(TEntity)); foreach (var kic in map.MapList) { var lstError = new List <string>(); var value = PropertyGetCacheManger.Cache(kic.Key, entity); // 是否必填 if (kic.Value.Required != null && !kic.Value.Required.IsValid(value)) { lstError.Add(kic.Value.Required.ErrorMessage); } //if (value == null) { continue; } // 字符串长度判断 if (kic.Value.StringLength != null && !kic.Value.StringLength.IsValid(value)) { lstError.Add(kic.Value.StringLength.ErrorMessage); } // 值的长度 if (kic.Value.Range != null && !kic.Value.Range.IsValid(value)) { lstError.Add(kic.Value.Range.ErrorMessage); } // 正则 if (kic.Value.RegularExpression != null && !kic.Value.RegularExpression.IsValid(value)) { lstError.Add(kic.Value.RegularExpression.ErrorMessage); } if (lstError.Count > 0) { dicError.Add(kic.Key.Name, lstError); } } return(dicError.Count == 0); }
/// <summary> /// 将集合类转换成DataTable /// </summary> /// <param name="lst">集合</param> /// <returns></returns> public static DataTable ToTable <TEntity>(this List <TEntity> lst) where TEntity : class { var dt = new DataTable(); if (lst.Count == 0) { return(dt); } var map = SetMapCacheManger.Cache(typeof(TEntity)); var lstFields = map.MapList.Where(o => o.Value.Field.IsMap).ToList(); foreach (var field in lstFields) { var type = field.Key.PropertyType; // 对 List 类型处理 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { type = type.GetGenericArguments()[0]; } dt.Columns.Add(field.Value.Field.Name, type); } foreach (var info in lst) { dt.Rows.Add(dt.NewRow()); foreach (var field in lstFields) { var value = ConvertHelper.GetValue(info, field.Key.Name, (object)null); if (value == null) { continue; } if (!dt.Columns.Contains(field.Value.Field.Name)) { dt.Columns.Add(field.Value.Field.Name); } dt.Rows[dt.Rows.Count - 1][field.Value.Field.Name] = value; } } return(dt); }
/// <summary> /// 将XML转成实体 /// </summary> public static List <TEntity> ToList <TEntity>(this XElement element) where TEntity : class { var orm = SetMapCacheManger.Cache(typeof(TEntity)); var list = new List <TEntity>(); foreach (var el in element.Elements()) { var t = (TEntity)Activator.CreateInstance(typeof(TEntity)); //赋值字段 foreach (var kic in orm.MapList) { var type = kic.Key.PropertyType; if (!kic.Key.CanWrite) { continue; } //switch (kic.Value.PropertyExtend) { //case eumPropertyExtend.Attribute: // if (el.Attribute(kic.Value.Name) == null) { continue; } //kic.Key.SetValue(t, el.Attribute(kic.Value.Name).Value.ConvertType(type), null); // PropertySetCacheManger.Cache(kic.Key, t, el.Attribute(kic.Value.Name).Value.ConvertType(type)); // break; // case eumPropertyExtend.Element: if (el.Element(kic.Value.Field.Name) == null) { continue; } //kic.Key.SetValue(t, el.Element(kic.Value.Name).Value.ConvertType(type), null); PropertySetCacheManger.Cache(kic.Key, t, el.Element(kic.Value.Field.Name).Value.ConvertType(type)); break; } } list.Add(t); } return(list); }
/// <summary> /// 获取字段名称 /// </summary> /// <param name="select">字段名称</param> /// <returns></returns> public static string GetUsedName <T1, T2>(this Expression <Func <T1, T2> > select) where T1 : class { MemberExpression memberExpression; var unary = @select.Body as UnaryExpression; if (unary != null) { memberExpression = unary.Operand as MemberExpression; } else if (@select.Body.NodeType == ExpressionType.Call) { memberExpression = (MemberExpression)((MethodCallExpression)@select.Body).Object; } else { memberExpression = @select.Body as MemberExpression; } var map = SetMapCacheManger.Cache(typeof(T1)); var modelInfo = map.GetState((memberExpression.Member).Name); return(modelInfo.Value.Field.Name); }
/// <summary> /// 关系映射 /// </summary> /// <param name="type">实体类Type</param> public ContextPhysicsMap(Type type) { Type = type; // 当前调用的程序集,用于判断是否属于farseer.net.dll程序集 var currentAssembly = Assembly.GetCallingAssembly(); // 遍历所有Set属性(表、视图、存储过程的名称),取得对应使用标记名称 foreach (var propertyInfo in Type.GetProperties(BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.GetProperty | BindingFlags.Public)) { // 必须是farseer.net.dll程序集 if (!propertyInfo.CanWrite || propertyInfo.PropertyType.Assembly != currentAssembly || (propertyInfo.DeclaringType != null && propertyInfo.DeclaringType.Assembly == currentAssembly)) { continue; } // 设置每个Set属性(目前有Set是非泛型的) EntityMapList[propertyInfo] = propertyInfo.PropertyType.IsGenericType ? SetMapCacheManger.Cache(propertyInfo.PropertyType.GetGenericArguments()[0]) : null; } }
/// <summary> /// 根据TEntity实体,动态生成派生类 /// </summary> private Type BuildEntity(Type entityType) { //var entityType = typeof(TEntity); var setPhysicsMap = SetMapCacheManger.Cache(entityType); // new SetPhysicsMap(entityType); var clsName = entityType.Name + "ByDataRow"; // 类名 var sb = new StringBuilder(); #if !CORE sb.AppendLine("using System;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using FS.Core;"); sb.AppendLine("using FS.Utils.Common;"); sb.AppendLine("using FS.Data.Infrastructure;"); sb.AppendLine($"namespace {entityType.Namespace}\r\n{{"); #endif sb.AppendLine($"public class {clsName} : {entityType.FullName}\r\n{{"); // DataRow构造 sb.AppendLine(CreateToList(entityType)); // DataTable构造 sb.AppendLine(CreateToEntity(entityType, setPhysicsMap)); sb.AppendLine("}"); #if !CORE sb.AppendLine("}"); #endif #if !CORE CompilerResults results = null; try { var compilerParams = new CompilerParameters { CompilerOptions = "/target:library /optimize", //编译器选项设置 GenerateInMemory = true, //编译时在内存输出 IncludeDebugInformation = false //生成调试信息 }; //添加相关的引用 compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.dll"); compilerParams.ReferencedAssemblies.Add("System.Xml.dll"); var ass = AppDomain.CurrentDomain.GetAssemblies(); // 得到当前所有程序集 compilerParams.ReferencedAssemblies.Add(ass.FirstOrDefault(o => o.ManifestModule.Name == "Farseer.Net.dll")?.Location); compilerParams.ReferencedAssemblies.Add(ass.FirstOrDefault(o => o.ManifestModule.Name == "Farseer.Net.Core.dll")?.Location); compilerParams.ReferencedAssemblies.Add(ass.FirstOrDefault(o => o.ManifestModule.Name == "Farseer.Net.Data.dll")?.Location); // 加载成员依赖的类型所在的程序集 var properties = entityType.GetProperties(); foreach (var propertyInfo in properties) { // 找到真实程序集 var declaringType = propertyInfo.PropertyType.GetNullableArguments(); while (declaringType.IsGenericType) { declaringType = declaringType.GetGenericType(); } compilerParams.ReferencedAssemblies.Add(declaringType.Assembly.Location); } // 需要把基类型的dll,也载进来 var baseType = entityType; while (baseType != null) { compilerParams.ReferencedAssemblies.Add(baseType.Assembly.Location); baseType = baseType.BaseType; } var compiler = CodeDomProvider.CreateProvider("CSharp"); //编译 results = compiler.CompileAssemblyFromSource(compilerParams, sb.ToString()); return(results.CompiledAssembly.GetExportedTypes()[0]); } catch (Exception exp) { if (results != null) { var error = new string[results.Errors.Count]; for (int i = 0; i < error.Length; i++) { error[i] = results.Errors[i].ErrorText; IocManager.Instance.Logger.Error(error[i]); } throw new Exception(error.ToString(",")); } IocManager.Instance.Logger.Error(exp.ToString()); throw exp; } #else var scriptOptions = ScriptOptions.Default; scriptOptions = scriptOptions.AddReferences(typeof(List <>).Assembly, typeof(ConvertHelper).Assembly, typeof(MapingData).Assembly, entityType.Assembly); scriptOptions = scriptOptions.AddImports("System.Collections.Generic"); scriptOptions = scriptOptions.AddImports("FS.Core"); scriptOptions = scriptOptions.AddImports("FS.Utils.Common"); scriptOptions = scriptOptions.AddImports("FS.Data.Infrastructure"); // 加载成员依赖的类型所在的程序集 var properties = entityType.GetProperties(); foreach (var propertyInfo in properties) { // 找到真实程序集 var declaringType = propertyInfo.PropertyType.GetNullableArguments(); while (declaringType.IsGenericType) { declaringType = declaringType.GetGenericType(); } scriptOptions = scriptOptions.AddReferences(declaringType.Assembly); } // 需要把基类型的dll,也载进来 var baseType = entityType; while (baseType != null) { scriptOptions = scriptOptions.AddReferences(baseType.Assembly); baseType = baseType.BaseType; } var scriptState = CSharpScript.Create(sb.ToString(), scriptOptions).RunAsync().Result; var asmName = scriptState.Script.GetCompilation().AssemblyName; var assembly = AppDomain.CurrentDomain.GetAssemblies().First(a => a.FullName.StartsWith(asmName, StringComparison.OrdinalIgnoreCase)); return(assembly.DefinedTypes.FirstOrDefault(o => o.Name == clsName)); #endif }