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 > )
{
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 > )
{
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 > )
{
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) > -)
{
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 > )
{
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[];
if (dt.Rows.Count > )
{
return ToModel<T>(dt.Rows[]);
}
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[];
List<T> list = new List<T>();
if (dt.Rows.Count > )
{
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 > )
{
obValue = objInfo[].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[].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 > ) {#>.<#= host.Folder #><# } #>
{
<# if( host.TableDescription.Length > ) {#>
//<#= 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#>"; }
}
像删除和修改的一些代码没有顾得上去添加
C#用扩展方法进行自动生成添加删除对象转换的功能的更多相关文章
- C#3.0新特性:隐式类型、扩展方法、自动实现属性,对象/集合初始值设定、匿名类型、Lambda,Linq,表达式树、可选参数与命名参数
一.隐式类型var 从 Visual C# 3.0 开始,在方法范围中声明的变量可以具有隐式类型var.隐式类型可以替代任何类型,编译器自动推断类型. 1.var类型的局部变量必须赋予初始值,包括匿名 ...
- Asp.net mvc 5 CRUD代码自动生成工具- vs.net 2013 Saffolding功能扩展
Asp.net mvc 5 CRUD代码自动生成工具 -Visual Studio.net2013 Saffolding功能扩展 上次做过一个<Asp.net webform scaffoldi ...
- IDEA类和方法注释自动生成
一.生成类注释 1.打开Preferences-->Editor-->File and Code Templates,右侧选择Filestab页,找到Class.Interface,可以看 ...
- docfx 简单使用方法、自动生成目录的工具
[摘要] 这是我编写的一个 Docfx 文档自动生成工具,只要写好 Markdown 文档,使用此工具可为目录.文件快速生成配置,然后直接使用 docfx 运行即可. https://github.c ...
- MyBatis Generator 自动生成的POJO对象的使用(二)
四.Example Class使用说明 示例类指定如何构建动态where子句. 表中的每个非BLOB列都可以选择包含在where子句中. 示例是演示此类用法的最佳方法. 示例类可用于生成几乎无限制的w ...
- MyBatis Generator 自动生成的POJO对象的使用(一)
MyBatis Generator 会自动生成以下几种类型的对象(除非你使用MyBatis3DynamicSql 的运行环境): Java Model Objects(总是生成) SQL Map Fi ...
- Eclipse自动生成作者、日期注释等功能设置
我们在使用Eclipse 编写Java代码时,自动生成的注释信息都是按照预先设置好的格式生成的. 修改作者.日期注释格式:打开Windows->Preferences->Java-> ...
- Eclipse自动补全功能和自动生成作者、日期注释等功能设置
修改作者.日期注释格式:打开Windows->Preferences->Java->Code Style->Code Templates,点击右边窗口中的Comments,可以 ...
- Eclipse自动生成作者、日期注释等功能设置(转载)
在使用Eclipse 编写Java代码时,自动生成的注释信息都是按照预先设置好的格式生成的. 修改作者.日期注释格式:打开Windows->Preferences->Java->Co ...
随机推荐
- vmware备忘
- MVC -- 后台RedirectToAction传递实体类与字符串
1.MVC -- 后台RedirectToAction传递实体类 RedirectToAction(控制器,控制器方法,实体类) 2.MVC -- 后台RedirectToAction传递字符串 Re ...
- angular1.x的简单介绍 (一)
angular1.x作为经典的mvc框架,可以创建能够复用的组件,也可进行双向数据绑定.国内的vue.js/avaloon.js都是同类型的框架.适合使用angularjs的项目有大型信息化管理系统: ...
- Ubuntu 14.04 更换阿里云源[转]
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak #备份 sudo vim /etc/apt/sources.list #修改 sudo ...
- JavaScript通过id获取不到元素是什么原因阿?
s代码 JavaScript code ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 function show_more_mess() { $(&qu ...
- Problem with "AnyConnect was not able to establish connection to the specified secure gateway."
Cisco的VPN客户端最近报"AnyConnect was not able to establish connection to the specified secure gateway ...
- 权限管理[Linux]
chown username file,... 改变文件的属主(只有管理员可以使用此命令) -R:修改目录及其内部文件的属主 -reference=somefile_path file,...把想要设 ...
- Quartz.Net简单使用
Quartz.Net为开源的作业调度框架,使用方便,实现IJob接口,及相关配置,即可实现调度. 项目包安装: install-package Quartz install-package log4n ...
- 【Gson】互相转化
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库.可以将一个 JSON 字符串转成一个 Java 对象,或者反过来. 对象转为字符串 Strin ...
- [转载] 构造linux 系统下免密码ssh登陆 _How to establish password-less login with SSH
In present (post production) IT infrastructure many different workstations, servers etc. have to be ...