国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

C#用擴(kuò)展方法進(jìn)行自動(dòng)生成添加刪除對(duì)象轉(zhuǎn)換的功能

2019-11-14 13:52:34
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
 public static class ExtendedModel    {        #region 實(shí)體類的增刪改查        #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 獲取實(shí)體類        /// <summary>        /// DataRow轉(zhuǎn)換實(shí)體類        /// </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轉(zhuǎn)換實(shí)體類        /// </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獲取實(shí)體類        /// </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獲取實(shí)體列表        /// </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 實(shí)體類轉(zhuǎn)換        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("實(shí)體轉(zhuǎn)換失敗")); ;            }        }        #endregion    }

調(diào)用方法

//datarow轉(zhuǎn)換對(duì)象VWB_Weight upModel = dt.Rows[0].ToModel<VWB_Weight>();//table轉(zhuǎn)換listList<VWB_Weight> upModel = dt.ToModelList<VWB_Weight>();upModel.Add();//一個(gè)對(duì)象轉(zhuǎn)換另一個(gè)對(duì)象AA a = upModel.EntityToT<AA>;

動(dòng)軟生成器模板

<#@ 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#>";    }}

 像刪除和修改的一些代碼沒(méi)有顧得上去添加


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 离岛区| 噶尔县| 苗栗市| 阿尔山市| 平武县| 怀仁县| 涿鹿县| 桃园县| 兴文县| 龙游县| 乌鲁木齐县| 广饶县| 武邑县| 紫金县| 扎兰屯市| 三台县| 马边| 广东省| 年辖:市辖区| 丹江口市| 阿图什市| 永清县| 杭州市| 星子县| 永丰县| 会昌县| 顺义区| 沙湾县| 弥渡县| 汝城县| 文成县| 年辖:市辖区| 于都县| 松潘县| 虎林市| 陆丰市| 城固县| 平罗县| 申扎县| 界首市| 乌兰察布市|