ASP.NET中实现根据匿名类、datatable、sql生成实体类
程序员文章站
2024-02-21 08:14:40
在开发中可能会遇到这几种情况:
1、ef或linq查询出来的匿名对象在其它地方调用不方便,又懒的手动建实体类
2、通过datatable反射实体需要先建一个类 ,头痛...
在开发中可能会遇到这几种情况:
1、ef或linq查询出来的匿名对象在其它地方调用不方便,又懒的手动建实体类
2、通过datatable反射实体需要先建一个类 ,头痛
3、通过sql语句返回的实体也需要先建一个类 ,头痛
4、如果通过代码生成器要写模版,需要安装或者不想生成一堆不用的类
为了解决上面的不便之处,我封装了一个实体生成类,可以扔到程序里面任意调用
封装类:
using system; using system.collections.generic; using system.linq; using system.text; using system.data; using system.data.sqlclient; using system.text.regularexpressions; namespace syntacticsugar { /// <summary> /// ** 描述:实体生成类 /// ** 创始时间:2015-4-17 /// ** 修改时间:- /// ** 作者:sunkaixuan /// ** qq:610262374 欢迎交流,共同提高 ,命名语法等写的不好的地方欢迎大家的给出宝贵建议 /// </summary> public class classgenerating { /// <summary> /// 根据匿名类获取实体类的字符串 /// </summary> /// <param name="entity">匿名对象</param> /// <param name="classname">生成的类名</param> /// <returns></returns> public static string dynamictoclass(object entity, string classname) { stringbuilder reval = new stringbuilder(); stringbuilder propertiesvalue = new stringbuilder(); var propertiesobj = entity.gettype().getproperties(); string replaceguid = guid.newguid().tostring(); string nullable = string.empty; foreach (var r in propertiesobj) { var type = r.propertytype; if (type.isgenerictype && type.getgenerictypedefinition() == typeof(nullable<>)) { type = type.getgenericarguments()[0]; nullable = "?"; } if (!type.namespace.contains("system.collections.generic")) { propertiesvalue.appendline(); string typename = changetype(type); propertiesvalue.appendformat("public {0}{3} {1} {2}", typename, r.name, "{get;set;}", nullable); propertiesvalue.appendline(); } } reval.appendformat(@" public class {0}{{ {1} }} ", classname, propertiesvalue); return reval.tostring(); } /// <summary> /// 根据datatable获取实体类的字符串 /// </summary> /// <param name="sql"></param> /// <param name="classname"></param> /// <returns></returns> public static string datatabletoclass(datatable dt, string classname) { stringbuilder reval = new stringbuilder(); stringbuilder propertiesvalue = new stringbuilder(); string replaceguid = guid.newguid().tostring(); foreach (datacolumn r in dt.columns) { propertiesvalue.appendline(); string typename = changetype(r.datatype); propertiesvalue.appendformat("public {0} {1} {2}", typename, r.columnname, "{get;set;}"); propertiesvalue.appendline(); } reval.appendformat(@" public class {0}{{ {1} }} ", classname, propertiesvalue); return reval.tostring(); } /// <summary> /// 根据sql语句获取实体类的字符串 /// </summary> /// <param name="sql">sql语句</param> /// <param name="classname">生成的类名</param> /// <param name="server">服务名</param> /// <param name="database">数据库名称</param> /// <param name="uid">账号</param> /// <param name="pwd">密码</param> /// <returns></returns> public static string sqltoclass(string sql, string classname, string server, string database, string uid, string pwd) { using (sqlconnection conn = new sqlconnection(string.format("server={0};uid={2};pwd={3};database={1}", server, database, uid, pwd))) { sqlcommand command = new sqlcommand(); command.connection = conn; command.commandtext = sql; datatable dt = new datatable(); sqldataadapter sad = new sqldataadapter(command); sad.fill(dt); var reval = datatabletoclass(dt, classname); return reval; } } /// <summary> /// 根据sql语句获取实体类的字符串 /// </summary> /// <param name="sql">sql语句</param> /// <param name="classname">生成的类名</param> /// <param name="connname">webconfig的connectionstrings name</param> /// <returns></returns> public static string sqltoclass(string sql, string classname, string connname) { string connstr = system.configuration.configurationmanager.connectionstrings[connname].tostring(); if (connstr.contains("metadata"))//ef connstr = regex.match(connstr, @"connection string\=""(.+)""").groups[1].value; using (sqlconnection conn = new sqlconnection(connstr)) { sqlcommand command = new sqlcommand(); command.connection = conn; command.commandtext = sql; datatable dt = new datatable(); sqldataadapter sad = new sqldataadapter(command); sad.fill(dt); var reval = datatabletoclass(dt, classname); return reval; } } /// <summary> /// 匹配类型 /// </summary> /// <param name="type"></param> /// <returns></returns> private static string changetype(type type) { string typename = type.name; switch (typename) { case "int32": typename = "int"; break; case "string": typename = "string"; break; } return typename; } } }
调用如下:
//通过匿名对象生成实体类 var dynamicobj = new { id = 1, name = "小名", entity = new enityt1() }; //注意:只能是单个实体不能传入 list<t> ,集合需要 list[0] string classcode = classgenerating.dynamictoclass(dynamicobj, "classdynamic"); //通过datatable生成实体类 datatable dt = new datatable(); dt.columns.add("id", typeof(int)); dt.columns.add("name"); classcode = classgenerating.datatabletoclass(dt, "classtatabale"); //通过sql语句生成实体类 classcode = classgenerating.sqltoclass("select * from note", "note", "127.0.0.1", "mywork", "sa", "sasa"); classcode = classgenerating.sqltoclass("select * from dbo.accessoriesdetail", "accessoriesdetail", "nfdentities");//通过 config connstring名称
然后在调试状态把你需要的结果ctrl+c 然后去新建一个类ctrl+v