利用ASP.NET怎么不行个根据匿名类和datatable
创始人
2024-11-28 21:03:28
0次

在开发中可能会遇到这几种情况:

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
{
  /// 
  /// ** 描述:实体生成类
  /// ** 创始时间:2015-4-17
  /// ** 修改时间:-
  /// ** 作者:sunkaixuan
  /// ** qq:610262374 欢迎交流,共同提高 ,命名语法等写的不好的地方欢迎大家的给出宝贵建议
  /// 
  public class ClassGenerating
  {
    /// 
    /// 根据匿名类获取实体类的字符串
    /// 
    /// 匿名对象
    /// 生成的类名
    /// 
    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();
    }
 
 
    /// 
    /// 根据DataTable获取实体类的字符串
    /// 
    /// 
    /// 
    /// 
    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();
    }
 
    /// 
    /// 根据SQL语句获取实体类的字符串
    /// 
    /// SQL语句
    /// 生成的类名
    /// 服务名
    /// 数据库名称
    /// 账号
    /// 密码
    /// 
    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;
      }
    }
    /// 
    /// 根据SQL语句获取实体类的字符串
    /// 
    /// SQL语句
    /// 生成的类名
    /// webconfig的connectionStrings name
    /// 
    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;
      }
    }
    /// 
    /// 匹配类型
    /// 
    /// 
    /// 
    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 ,集合需要  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

利用ASP.NET怎么不行个根据匿名类和datatable

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...