无为清净楼资源网 Design By www.qnjia.com

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

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

ASP.NET中实现根据匿名类、datatable、sql生成实体类

标签:
ASP.NET,匿名类,datatable,sql,生成实体类

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。