1、调用
public void Get(){User model = new User{user_name = "admin",nick_name = "king",password = "123456"};string result = GetProperties(model);string value = GetPropertyValue(model, "user_name");}
2、实体类
public class User{public string user_name { get; set; }public string nick_name { get; set; }public string password { get; set; }}
3、PropertyInfo 获取实体类的所有属性和值
public string GetProperties<T>(T t){string tStr = string.Empty;if (t == null){return tStr;}PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);if (properties.Length <= 0){return tStr;}foreach (PropertyInfo item in properties){string name = item.Name;object value = item.GetValue(t, null);if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")){tStr += string.Format("{0}:{1},", name, value);}else{GetProperties(value);}}return tStr;}
4、PropertyInfo 获取实体类指定属性值
public string GetPropertyValue<T>(T t, string field){string value = "9";if (t == null){return value;}PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);if (properties.Length <= 0){return value;}var property = properties.Where(x => x.Name == field).FirstOrDefault();value = property.GetValue(t, null).ToString();return value;}
5、类型判断
propertyInfo.PropertyType != typeof(int)
propertyInfo.PropertyType != typeof(double)
propertyInfo.PropertyType != typeof(DateTime?)
private readonly TestDbContext _context;public ReportsService(TestDbContext context){_context = context;}public IEnumerable<TestDto> Get(){_context.ExecuteProc<TestDto>("存储过程名称", 参数);}public static IEnumerable<TElement> ExecuteProc<TElement>(this TestDbContext db, string sql, params object[] parameters) where TElement : new(){var connection = db.Database.GetDbConnection();using (var cmd = connection.CreateCommand()){db.Database.OpenConnection();mandText = sql;mandType = mandType.StoredProcedure;cmd.Parameters.AddRange(parameters);var dr = cmd.ExecuteReader();var columnSchema = dr.GetColumnSchema();var data = new List<TElement>();while (dr.Read()){TElement item = new TElement();Type type = item.GetType();foreach (var kv in columnSchema){var propertyInfo = type.GetProperty(kv.ColumnName);if (kv.ColumnOrdinal.HasValue && propertyInfo != null){if (kv.ColumnName == "COLLECTOR_CODE"){ }var value = dr.IsDBNull(kv.ColumnOrdinal.Value) ? null : dr.GetValue(kv.ColumnOrdinal.Value);if (value == null){ }else{if (!string.IsNullOrEmpty(value.ToString())&& propertyInfo.PropertyType != typeof(int)&& propertyInfo.PropertyType != typeof(double)&& propertyInfo.PropertyType != typeof(DateTime?)){value = value.ToString();}}propertyInfo.SetValue(item, value);}}data.Add(item);}dr.Dispose();return data;}}
*
*
*