/// <summary> /// 通过实体类型获取实体信息 /// </summary> /// <param name="type"></param> /// <returns></returns> public EntityInfo GetEntity(Type type) { EntityInfo entityInfo = null; if (!_entityInfos.TryGetValue(type, out entityInfo)) { lock (_entityLocker) { entityInfo = new EntityInfo(); entityInfo.TableName = ExpressionUtil.GetEntityTableName(type); if (string.IsNullOrWhiteSpace(entityInfo.TableName)) { throw new Exception("实体必须标明TableAttribute"); } entityInfo.EntityType = type; var pis = ExpressionReflector.GetProperties(type).Values; foreach (var property in pis) { var foreignKeyAttr = AttributeHelper.GetAttribute <ForeignKeyAttribute>(property); if (foreignKeyAttr != null) { entityInfo.ForeignKeys.Add(property); } entityInfo.Properties.Add(property); } _entityInfos.Add(type, entityInfo); } } return(entityInfo); }
protected override Expression VisitLambda <T>(Expression <T> node) { if (node.Body is NewExpression) { //此处一般是在Select方法中new了匿名对象,例如users.Select(x=>new {x.Id}) return(base.VisitLambda <T>(node)); } //此处一般是在Select方法中直接选择了参数,例如users.Select(x=>x),这种情况下直接把x的所有列转换出来 var properties = ExpressionReflector.GetProperties(node.Body.Type).Values; foreach (var item in properties) { if (!ExpressionUtil.IsEntityPropertyType(item.PropertyType)) { continue; ////是否.Net自带的String、DateTime,如果不是则跳过 //if (!((item.PropertyType.FullName == "System.String" || item.PropertyType.FullName == "System.DateTime") && item.PropertyType.Assembly.GlobalAssemblyCache)) //{ // continue; //} ////是否可空,如果不是则跳过 //var type = Nullable.GetUnderlyingType(item.PropertyType); //if (type == null) //{ // continue; //} } _columnInfos.Add(item.Name, new KeyValuePair <string, string>(_masterTableName, item.Name)); } return(node); }
public static IList Map(Type objectType, DataSet ds) { var list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(objectType)); Dictionary <string, Action <object, object> > propertySetters = ExpressionReflector.GetSetters(objectType); var properties = ExpressionReflector.GetProperties(objectType); DataTable table = ds.Tables[0]; foreach (DataRow row in ds.Tables[0].Rows) { object local = null; if (objectType.IsSealed) { var parameterObjects = new List <object>(); foreach (DataColumn column in ds.Tables[0].Columns) { var obj = row[column]; if (obj == DBNull.Value) { obj = null; } parameterObjects.Add(obj); } local = ExpressionReflector.CreateInstance(objectType, parameterObjects.ToArray()); } else { local = ExpressionReflector.CreateInstance(objectType); foreach (DataColumn column in ds.Tables[0].Columns) { object obj2 = row[column]; if (obj2 != DBNull.Value) { var property = properties.Get(column.ColumnName); if (property == null) { continue; } Type propertyType = property.PropertyType; Type underlyingType = Nullable.GetUnderlyingType(propertyType); if (underlyingType == null) { underlyingType = propertyType; } if (underlyingType.IsEnum) { obj2 = Enum.Parse(underlyingType, Convert.ToString(obj2)); } else { obj2 = Convert.ChangeType(obj2, underlyingType); } propertySetters.Get(column.ColumnName)(local, obj2); } } } list.Add(local); } return(list); }
//public static void Invoke(object entity, string methodName, params object[] args) //{ // Type key = entity.GetType(); // Action<object, object[]> action = null; // if (_objectMethods.ContainsKey(key)) // { // Dictionary<string, Action<object, object[]>> dictionary = _objectMethods[key]; // if (dictionary.ContainsKey(methodName)) // { // action = dictionary[methodName]; // } // } // else // { // Dictionary<string, Action<object, object[]>> dictionary2 = new Dictionary<string, Action<object, object[]>>(); // _objectMethods.Add(key, dictionary2); // } // if (action == null) // { // ParameterExpression expression = Expression.Parameter(_objectType); // UnaryExpression expression2 = Expression.Convert(expression, key); // ParameterExpression array = Expression.Parameter(typeof(object[])); // List<Expression> list = new List<Expression>(); // MethodInfo method = key.GetMethod(methodName); // ParameterInfo[] parameters = method.GetParameters(); // for (int i = 0; i < parameters.Length; i++) // { // ParameterInfo info2 = parameters[i]; // UnaryExpression item = Expression.Convert(Expression.ArrayIndex(array, Expression.Constant(i)), parameters[i].ParameterType); // list.Add(item); // } // Expression instance = method.IsStatic ? null : Expression.Convert(expression, method.ReflectedType); // action = Expression.Lambda<Action<object, object[]>>(Expression.Call(instance, method, list.ToArray()), new ParameterExpression[] { expression, array }).Compile(); // _objectMethods[key].Add(methodName, action); // } // action(entity, args); //} public static List <TObject> Map <TObject>(DataSet ds) where TObject : class, new() { List <TObject> list = new List <TObject>(); Type objectType = typeof(TObject); Dictionary <string, Action <object, object> > propertySetters = ExpressionReflector.GetSetters(objectType); var properties = ExpressionReflector.GetProperties(objectType); DataTable table = ds.Tables[0]; foreach (DataRow row in ds.Tables[0].Rows) { TObject local = Activator.CreateInstance <TObject>(); foreach (string str in propertySetters.Keys) { object obj2 = row[str]; if (obj2 != DBNull.Value) { Type propertyType = properties[str].PropertyType; Type underlyingType = Nullable.GetUnderlyingType(propertyType); if (underlyingType == null) { underlyingType = propertyType; } if (underlyingType.IsEnum) { obj2 = Enum.Parse(underlyingType, Convert.ToString(obj2)); } else { obj2 = Convert.ChangeType(obj2, underlyingType); } propertySetters[str](local, obj2); } } list.Add(local); } return(list); }
public EntityResult <TModel> GetModelFromPost <TModel>() where TModel : class, new() { Type objectType = typeof(TModel); var propertySetters = ExpressionReflector.GetSetters(objectType); EntityResult <TModel> result = new EntityResult <TModel>(); var values = ExpressionReflector.GetProperties(objectType); NameValueCollection form = HttpContext.Current.Request.Form; TModel local = Activator.CreateInstance <TModel>(); foreach (PropertyInfo info in values.Values) { object obj2 = null; string str = info.Name.ToLower(); Type underlyingType = Nullable.GetUnderlyingType(info.PropertyType); ValidationAttribute[] attributes = AttributeHelper.GetAttributes <ValidationAttribute>(info); if (form.AllKeys.Contains <string>(str, StringComparer.InvariantCultureIgnoreCase)) { string str2 = form[str]; try { if (underlyingType != null) { obj2 = Convert.ChangeType(str2, underlyingType); } else { obj2 = Convert.ChangeType(str2, info.PropertyType); } } catch (FormatException) { } } else if (underlyingType == null) { //不是可空类型,必须要有一个值,所以应该提示一个错误 var requiredAttr = attributes.FirstOrDefault(x => x is RequiredAttribute); if (requiredAttr == null || string.IsNullOrWhiteSpace(requiredAttr.ErrorMessage)) { result.Message = "表单项 " + info.Name + " 验证失败"; } else { result.Message = requiredAttr.ErrorMessage; } return(result); } foreach (ValidationAttribute attribute in attributes) { if (!((attribute == null) || attribute.IsValid(obj2))) { result.Message = string.IsNullOrEmpty(attribute.ErrorMessage) ? ("表单项 " + info.Name + " 验证失败") : attribute.ErrorMessage; return(result); } } if ((obj2 == null) && (underlyingType == null)) { try { obj2 = Activator.CreateInstance(info.PropertyType); } catch (MissingMethodException) { obj2 = null; } } propertySetters[info.Name](local, obj2); } result.Model = local; result.Success = true; return(result); }
public static List <T> Import <T>(Stream stream, Func <string, string, string> onImportItemPropertyData, Action <T> onImportItemData) where T : class, new() { HSSFWorkbook book = new HSSFWorkbook(stream); Type type = typeof(T); var piDict = ExpressionReflector.GetProperties(type); var attrsDict = new Dictionary <string, string>(); var properties = new Dictionary <int, string>(); foreach (var propertyInfo in piDict.Values) { var attr = AttributeHelper.GetAttribute <DataGridColumnAttribute>(propertyInfo); if (attr == null) { continue; } attrsDict.Add(attr.DisplayName, propertyInfo.Name); } Dictionary <int, Action <object, object> > settersMapped = new Dictionary <int, Action <object, object> >(); var setters = ExpressionReflector.GetSetters(type); ISheet sheet = book.GetSheetAt(0); IRow headerRow = sheet.GetRow(0); for (int i = 0; i < headerRow.Cells.Count; i++) { ICell cell = headerRow.Cells[i]; string name = cell.StringCellValue.ToLower(); if (attrsDict.ContainsKey(name)) { name = attrsDict[name].ToLower(); } foreach (var key in setters.Keys.Where(key => key.ToLower() == name)) { settersMapped.Add(i, setters[key]); properties.Add(i, name); break; } } List <T> list = new List <T>(); for (int i = 1; i <= sheet.LastRowNum; i++) { T t = new T(); if (onImportItemData != null) { onImportItemData(t); } var cells = sheet.GetRow(i).Cells; for (int j = 0; j < cells.Count; j++) { string value = cells[j].ToString(); if (onImportItemPropertyData != null) { value = onImportItemPropertyData(value, properties[j]); } settersMapped[j](t, value); } list.Add(t); } return(list); //ISheet sheet= book.CreateSheet(); //var header= sheet.CreateRow(0); //for (int i = 0; i < properties.Count; i++) //{ // ICell cell= header.CreateCell(i); // string name = properties[i]; // if (attrsDict.ContainsKey(name)) // { // name = attrsDict[properties[i]].DisplayName; // } // cell.SetCellValue(name); //} }
public static Utils.Entity.EntityResult <TModel> Validate <TModel>(Form form) where TModel : class, new() { var controls = form.GetControls(); EntityResult <TModel> er = new EntityResult <TModel>(); var pis = ExpressionReflector.GetProperties(typeof(TModel)); TModel model = new TModel(); foreach (Control item in controls.Values) { if (item is TextBox) { var prefix = GetControlPrefix <TextBox>(); var propertyPair = pis.Where(x => item.Name == prefix + x.Value.Name).FirstOrDefault(); if (string.IsNullOrEmpty(propertyPair.Key)) { continue; } var propertyInfo = propertyPair.Value; Type propertyType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); if (propertyType == null) { propertyType = propertyInfo.PropertyType; } object value = item.Text; value = Convert.ChangeType(value, propertyType); var attrs = AttributeHelper.GetAttributes <ValidationAttribute>(propertyInfo); foreach (var attr in attrs) { if (attr != null && !attr.IsValid(value)) { er.Message = string.IsNullOrEmpty(attr.ErrorMessage) ? ("表单项" + item.Name + "验证失败") : attr.ErrorMessage; return(er); } } ExpressionReflector.SetValue(model, propertyPair.Key, value); } else if (item is NumericUpDown) { var prefix = GetControlPrefix <NumericUpDown>(); var propertyPair = pis.Where(x => item.Name == prefix + x.Value.Name).FirstOrDefault(); if (string.IsNullOrEmpty(propertyPair.Key)) { continue; } var propertyInfo = propertyPair.Value; Type propertyType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); if (propertyType == null) { propertyType = propertyInfo.PropertyType; } object value = item.Text; value = Convert.ChangeType(value, propertyType); var attrs = AttributeHelper.GetAttributes <ValidationAttribute>(propertyInfo); foreach (var attr in attrs) { if (attr != null && !attr.IsValid(value)) { er.Message = string.IsNullOrEmpty(attr.ErrorMessage) ? ("表单项" + item.Name + "验证失败") : attr.ErrorMessage; return(er); } } ExpressionReflector.SetValue(model, propertyPair.Key, value); } else if (item is ComboBox) { var prefix = GetControlPrefix <ComboBox>(); var propertyPair = pis.Where(x => item.Name == prefix + x.Value.Name).FirstOrDefault(); if (string.IsNullOrEmpty(propertyPair.Key)) { continue; } var propertyInfo = propertyPair.Value; Type propertyType = Nullable.GetUnderlyingType(propertyInfo.PropertyType); if (propertyType == null) { propertyType = propertyInfo.PropertyType; } object value = item.Text; value = Convert.ChangeType(value, propertyType); var attrs = AttributeHelper.GetAttributes <ValidationAttribute>(propertyInfo); foreach (var attr in attrs) { if (attr != null && !attr.IsValid(value)) { er.Message = string.IsNullOrEmpty(attr.ErrorMessage) ? ("表单项" + item.Name + "验证失败") : attr.ErrorMessage; return(er); } } ExpressionReflector.SetValue(model, propertyPair.Key, value); } } er.Model = model; er.Success = true; return(er); }
internal void Visit() { Visit(expression); //获取表名 Type elementType = null; MethodCallExpression call = expression as MethodCallExpression; while (true) { var exp = call.Arguments[0]; if (exp is MethodCallExpression) { call = exp as MethodCallExpression; continue; } if (exp is ConstantExpression) { var constExp = exp as ConstantExpression; elementType = constExp.Type.GetGenericArguments()[0]; break; } throw new Exception("获取表达式树表名的时候出错"); } var entityInfo = _entityManager.GetEntity(elementType); //var tableAttr = (TableAttribute)elementType.GetCustomAttributes(_tableAttrType, true).FirstOrDefault(); //string tableName = elementType.Name + "s"; //if (tableAttr != null) //{ // tableName = tableAttr.TableName; //} StringBuilder sb = new StringBuilder("select "); Dictionary <string, string> aliaTableNameMap = new Dictionary <string, string>(); //先执行Select,必须执行 if (_expressionDict.ContainsKey("Select")) { selectorVisitor = new SelectExpressionVisitor(entityInfo, _expressionDict["Select"]); selectorVisitor.Visit(); _columns = string.Join(",", selectorVisitor.Columns); _alias = selectorVisitor.Alias; aliaTableNameMap = selectorVisitor.TableInfos; selectorVisitor.ClearResult(); } else { var type = expression.Type.GetGenericArguments()[0]; var pis = ExpressionReflector.GetProperties(type).Values; _alias = pis.Select(x => x.Name).ToList(); _columns = string.Join(",", _alias.Select(x => "[" + x + "]")); aliaTableNameMap.Add(entityInfo.TableName, entityInfo.TableName); } //再执行Where,可以没有 //Parameters = new Dictionary<string, object>(); //if (_expressionDict.ContainsKey("Where")) //{ // var whereVisitor = new WhereExpressionVisitor(aliaTableNameMap, _expressionDict["Where"]); // whereVisitor.Visit(); // condition = whereVisitor.Condition; // Parameters = whereVisitor.Parameters; //} ////先解析为查询 StringBuilder childSelect = new StringBuilder("select "); childSelect.Append(string.Join(",", _columns)); //childSelect.Append(" from " + tableName); //是否需要包装成子查询 if (selectorVisitor != null && selectorVisitor.NeedWrapSelect) { //拼接主查询 sb.Append(string.Join(" , ", _alias)); sb.AppendFormat(" from ({0}) t ", childSelect.ToString()); } else { sb = childSelect; } if (!string.IsNullOrEmpty(condition)) { sb.Append(" where "); sb.Append(condition); } CommandText = sb.ToString(); }