程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#用擴展方法進行自動生成添加刪除對象轉換的功能,

C#用擴展方法進行自動生成添加刪除對象轉換的功能,

編輯:C#入門知識

C#用擴展方法進行自動生成添加刪除對象轉換的功能,


 public static class ExtendedModel
    {
        #region 實體類的增刪改查
        #region 添加
        public static 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


    }

調用方法

//datarow轉換對象
VWB_Weight upModel = dt.Rows[0].ToModel<VWB_Weight>();
//table轉換list
List<VWB_Weight> upModel = dt.ToModelList<VWB_Weight>();

upModel.Add();
//一個對象轉換另一個對象
AA a = upModel.EntityToT<AA>;

動軟生成器模板

<#@ template language="c#" HostSpecific="True" #>
<#@ output extension= ".cs" #>
<#
    TableHost host = (TableHost)(Host);
    host.Fieldlist.Sort(CodeCommon.CompareByintOrder);
#>
using System; 
using System.Text;
using System.Collections.Generic; 
using System.Data;
namespace <#= host.NameSpace #>.Model<# if( host.Folder.Length > 0) {#>.<#= host.Folder #><# } #>
{
    <# if( host.TableDescription.Length > 0) {#>
    //<#= host.TableDescription #>
    <# } #>
    public class <#= host.GetModelClass(host.TableName) #>
    {

        <# foreach (ColumnInfo c in host.Fieldlist)
        { #>/// <summary>
        /// <#= string.IsNullOrEmpty(c.Description) ? c.ColumnName : c.Description #>
        /// </summary>        
        private <#= CodeCommon.DbTypeToCS(c.TypeName) #> _<#= c.ColumnName.ToString().ToLower() #>;
        public <#= CodeCommon.DbTypeToCS(c.TypeName) #> <#= c.ColumnName #>
        {
            get{ return _<#= c.ColumnName.ToString().ToLower()#>; }
            set{ _<#= c.ColumnName.ToString().ToLower() #> = value; }
        }        
        <# } #>
        public string PrimaryKey="<# foreach (ColumnInfo c in host.Keys)
            { #><#= c.ColumnName #>,<#}#>".TrimEnd(',');
public string IdentityStr = "<# for(int i=0;i< host.Fieldlist.Count;i++) {   ColumnInfo c = host.Fieldlist[i]; if (c.IsIdentity) {#><#= c.ColumnName#><# if (i< host.Fieldlist.Count-1 ) {#>,<#}#><#}}#>".TrimEnd(',');

        public string IdentityKey="<#= host.IdentityKey==null?"":host.IdentityKey.ColumnName#>";

    }
}

 像刪除和修改的一些代碼沒有顧得上去添加

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved