你的位置:首页 > 软件开发 > ASP.net > C#用扩展方法进行自动生成添加删除对象转换的功能

C#用扩展方法进行自动生成添加删除对象转换的功能

发布时间:2015-10-26 19:00:39
public static class ExtendedModel { #region 实体类的增删改查 #region 添加 public static string AddStr(this object t) { StringBuilder ...
 public static class ExtendedModel  {    #region 实体类的增删改查    #region 添加    public static get='_blank'>string AddStr(this object t)    {      StringBuilder strSql = new StringBuilder();      StringBuilder strSql1 = new StringBuilder();      StringBuilder strSql2 = new StringBuilder();      FieldInfo PrimaryKeyInfo = t.GetType().GetField("PrimaryKey");      FieldInfo IdentityStrInfo = t.GetType().GetField("IdentityStr");      string IdentityStr = "";      if (IdentityStrInfo != null)      {        IdentityStr = IdentityStrInfo.GetValue(t).ToString();      }      foreach (var item in t.GetType().GetProperties())      {        if (IdentityStr != item.Name && item.PropertyType != typeof(System.Byte[]))        {          strSql1.Append(item.Name + ",");          if (item.PropertyType == typeof(string) || item.PropertyType == typeof(DateTime) || item.PropertyType == typeof(Nullable <DateTime>) || item.PropertyType == typeof(bool))          {            if (item.PropertyType == typeof(DateTime) || item.PropertyType == typeof(Nullable<DateTime>))            {              DateTime datetime = (DateTime)item.GetValue(t, null);              if (datetime>DateTime.Parse("1900-01-01"))              {                strSql2.Append("'" + datetime.ToString("yyyy-MM-dd HH:mm:ss") + "',");              }              else              {                strSql2.Append("'1900-01-01',");              }                          }            else            {              strSql2.Append("'" + item.GetValue(t, null) + "',");            }                      }          else          {            object value = item.GetValue(t, null);            if (value != null)            {              strSql2.Append(value + ",");            }            else            {              strSql2.Append("0,");            }          }        }      }      strSql.Append("insert into " + t.GetType().Name + "(");      strSql.Append(strSql1.ToString().TrimEnd(','));      strSql.Append(")");      strSql.Append(" values (");      strSql.Append(strSql2.ToString().TrimEnd(','));      strSql.Append(")");      return strSql.ToString();    }    public static bool Add(this object t)    {      int istrue = DbHelperSQL.ExecuteSql(AddStr(t));      if (istrue > 0)      {        return true;      }      else      {        return false;      }    }    #endregion    #region 删除    public static string DeleteStr<T>(this T t, string Fields)    {      Type type = t.GetType();      string str = "delete " + type.Name;      if (!string.IsNullOrEmpty(Fields))      {        str += " where 1=1 ";        foreach (string item in Fields.Split(','))        {          PropertyInfo info = type.GetProperty(item);          str += string.Format(" and {0}='{1}'", info.Name, info.GetValue(t, null));        }      }      return str;    }    public static string DeleteWhereStr<T>(this T t, string sqlWhere) where T : new()    {      Type type = t.GetType();      string str = "delete " + type.Name + " ";      if (!string.IsNullOrEmpty(sqlWhere))      {        str += sqlWhere;      }      return str;    }    public static bool Delete<T>(this T t, string Fields)    {      int istrue = DbHelperSQL.ExecuteSql(DeleteStr(t, Fields));      if (istrue > 0)      {        return true;      }      else      {        return false;      }    }    public static bool DeleteWhere<T>(this T t, string sqlWhere) where T : new()    {      int istrue = DbHelperSQL.ExecuteSql(DeleteWhereStr(t, sqlWhere));      if (istrue > 0)      {        return true;      }      else      {        return false;      }    }    #endregion    #endregion    #region 获取实体类    /// <summary>    /// DataRow转换实体类    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="row"></param>    /// <returns></returns>    public static T ToModel<T>(this DataRow row) where T : new()    {      T t = new T();      foreach (var item in t.GetType().GetProperties())      {        if (row.Table.Columns.IndexOf(item.Name) > -1)        {          if (row[item.Name] != null && typeof(System.DBNull) != row[item.Name].GetType())          {            if (typeof(System.Byte) == row[item.Name].GetType())            {              if (item.PropertyType == typeof(System.Nullable<int>) || item.PropertyType == typeof(int))              {                item.SetValue(t,Convert.ToInt32(row[item.Name]), null);              }                          }            else            {              item.SetValue(t, Convert.ChangeType(row[item.Name], item.PropertyType), null);            }          }          else if (typeof(System.DateTime) == item.PropertyType)          {            item.SetValue(t, DateTime.Parse("1999-12-12"), null);          }        }      }      return t;    }    /// <summary>    /// DataRow转换实体类    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="row"></param>    /// <returns></returns>    public static List<T> ToModelList<T>(this DataTable dt) where T : new()    {      List<T> list = new List<T>();      if (dt.Rows.Count > 0)      {        foreach (DataRow item in dt.Rows)        {          list.Add(ToModel<T>(item));        }      }      return list;    }    /// <summary>    /// 查询Where获取实体类    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="strWhere"></param>    /// <returns></returns>    public static T Model<T>(this T t, string strWhere)      where T : class,new()    {      string str = "select top 1 * from " + typeof(T).Name + " " + strWhere;      DataTable dt = DbHelperSQL.Query(str).Tables[0];      if (dt.Rows.Count > 0)      {        return ToModel<T>(dt.Rows[0]);      }      else      {        return null;      }    }    /// <summary>    /// 查询Where获取实体列表    /// </summary>    /// <typeparam name="T"></typeparam>    /// <param name="strWhere"></param>    /// <returns></returns>    public static List<T> ModelList<T>(this T t, string strWhere)      where T : class,new()    {      string str = "select * from " + typeof(T).Name + " " + strWhere;      DataTable dt = DbHelperSQL.Query(str).Tables[0];      List<T> list = new List<T>();      if (dt.Rows.Count > 0)      {        foreach (DataRow item in dt.Rows)        {          list.Add(ToModel<T>(item));        }      }      return list;    }    #endregion    #region 实体类转换    public static T EntityToT<T, TT>(this TT tt) where T : new()    {      T t = new T();      List<PropertyInfo> listT = t.GetType().GetProperties().ToList();      List<PropertyInfo> listObj = tt.GetType().GetProperties().ToList();      foreach (var item in listT)      {        object value = SetPropertyValue(item, listObj, tt);        item.SetValue(t, value, null);      }      return t;    }    private static object SetPropertyValue(PropertyInfo info, List<PropertyInfo> listObj, object obj)    {      try      {        object obValue = null;        Type type = info.PropertyType;        List<PropertyInfo> objInfo = listObj.Where(c => c.Name.ToLower() == info.Name.ToLower()).ToList();        if (objInfo.Count > 0)        {          obValue = objInfo[0].GetValue(obj, null);          if (type == typeof(decimal) || type == typeof(Decimal))          {            if (obValue != null)            {              obValue = decimal.Parse(obValue.ToString());            }          }          else if (type == typeof(int))          {            if (obValue != null)            {              obValue = int.Parse(obValue.ToString());            }          }          else if (type == typeof(DateTime))          {            if (obValue != null)            {              DateTime date = new DateTime();              if (DateTime.TryParse(obValue.ToString(), out date))              {                obValue = date;              }              else              {                obValue = DateTime.Parse("1999-12-12");              }            }            else            {              obValue = DateTime.Parse("1999-12-12");            }          }        }        return obValue;      }      catch (Exception ex)      {        throw new Exception(string.Format("实体转换失败")); ;      }    }    #endregion  }

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:C#用扩展方法进行自动生成添加删除对象转换的功能

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录