123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace DapperORMCore.Dapper
- {
- /// <summary>
- /// 操作属性管理
- /// </summary>
- public class PropertyManage
- {
- /// <summary>
- /// Key对应结果
- /// </summary>
- /// <param name="keys"></param>
- /// <param name="separator"></param>
- /// <returns></returns>
- public static string GetSqlPairs
- (IEnumerable<string> keys, string separator = ", ")
- {
- var pairs = keys.Select(key => string.Format("{0}=@{0}", key)).ToList();
- return string.Join(separator, pairs);
- }
- /// <summary>
- /// 设置Id
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obj"></param>
- /// <param name="id"></param>
- /// <param name="propertyPairs"></param>
- public static void SetId<T>(T obj, int id, IDictionary<string, object> propertyPairs)
- {
- //对象属性
- if (propertyPairs.Count == 1)
- {
- var propertyName = propertyPairs.Keys.First();
- var propertyInfo = obj.GetType().GetProperty(propertyName);
- if (propertyInfo.PropertyType == typeof(int))
- {
- propertyInfo.SetValue(obj, id, null);
- }
- }
- }
- /// <summary>
- /// 检索具有名称和值的字典
- /// 与给定条件匹配的所有对象属性。
- /// </summary>
- public static PropertyContainer ParseProperties<T>(T obj)
- {
- var propertyContainer = new PropertyContainer();
- var typeName = typeof(T).Name;
- var validKeyNames = new[] { "Id",
- string.Format("{0}Id", typeName), string.Format("{0}_Id", typeName) };
- var properties = typeof(T).GetProperties();
- foreach (var property in properties)
- {
- // Skip reference types (but still include string!)
- if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
- continue;
- // Skip methods without a public setter
- if (property.GetSetMethod() == null)
- continue;
- // Skip methods specifically ignored
- if (property.IsDefined(typeof(DapperIgnore), false))
- continue;
- var name = property.Name;
- var value = typeof(T).GetProperty(property.Name).GetValue(obj, null);
- if (property.IsDefined(typeof(DapperKey), false) || validKeyNames.Contains(name))
- {
- propertyContainer.AddId(name, value);
- }
- else
- {
- propertyContainer.AddValue(name, value);
- }
- }
- return propertyContainer;
- }
- }
- }
|