Asp. NET implementation based on anonymous class, DataTable, SQL generated entity class _ Practical skills

Source: Internet
Author: User
Tags anonymous

There are several scenarios that you might encounter in development:

1, the EF or LINQ query anonymous objects in other places to call inconvenient, and lazy manually build entity classes

2, through the DataTable reflection entities need to first build a class, headache

3, the entity returned through the SQL statement also need to build a class, headache

4, if the code generator to write templates, you need to install or do not want to generate a bunch of unused classes

In order to solve the above inconvenience, I encapsulated an entity generated class, can be thrown into the program arbitrary call

Encapsulation class:

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>///* * Description: Entity Generation class///* * Founder Time: 2015-4-17///* * Modified time:-///* * Author: Sun 
    KaiXuan///* * qq:610262374 welcome the Exchange, common improvement, naming grammar and other bad written places welcome everyone to give valuable suggestions///</summary> public class Classgenerating { <summary>///A string of entity classes based on anonymous classes///</summary>///<param name= "entity" > Anonymous Objects </param >///<param name= "ClassName" > Generated class name </param>///<returns></returns> public static S
      Tring 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>///Gets the string of entity classes based on the DataTable///</summary>///<param name= "SQL" ></p aram>///<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>///Gets the string///</summary>///<param name= "SQL" &GT;SQL statement based on the SQL statement &LT;/PA
    ram>///<param name= "ClassName" > Generated class name </param>///<param name= "Server" > Service name </param> <param name= "Database" > Name </param>///<param name= "UID" > account &Lt;/param>///<param name= "pwd" > Password </param>///<returns></returns> public Static St Ring Sqltoclass (String sql, String className, String server, String database, String uid, string pwd) {using (S Qlconnection conn = new SqlConnection (String. Format ("Server={0};uid={2};p wd={3};d atabase={1}", Server, Database, UID, pwd)) {SqlCommand command = new S
        Qlcommand (); 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>///gets the string of entity classes based on SQL statements///</summary>///<param name= "SQL" >sql statements ;/param>///<param name= "ClassName" > Generated class name </param>///<param name= "Connname" >webconfig Ctionstrings 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>///match type///</summary>///<param name= "type" ></param> <returns></returns> private static string changetype (type type) {string typeName = type.
      Name;
    Switch (typeName)  {case "Int32": typeName = "int"; Case "string": TypeName = "string";
      Break
    return typeName;
 }
  }
}


The call is as follows:

Entity classes are generated via anonymous objects
      var dynamicobj = new {id = 1, name = "nickname", Entity = new Enityt1 ()};
      Note: Only a single entity cannot pass in List<t>, the collection requires  list[0]
      string classcode = Classgenerating.dynamictoclass (Dynamicobj, " Classdynamic ");


      Generating entity class
      datatable dt = new DataTable via DataTable ();
      Dt. Columns.Add ("Id", typeof (int));
      Dt. Columns.Add ("Name");

      Classcode = classgenerating.datatabletoclass (dt, "Classtatabale");


      Generate entity classes via SQL statements
      Classcode = Classgenerating.sqltoclass ("SELECT * from note", "note", "127.0.0.1", "MyWork", "sa", " Sasa "); 
      Classcode = Classgenerating.sqltoclass ("SELECT * FROM dbo.") Accessoriesdetail "," Accessoriesdetail "," nfdentities ");//through config connstring name

Then in the debug state put the results you need CTRL + C then go to a new class Ctrl + V


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.