Self-compiled DAL three-tier code generator and dal three-tier Code Generator

Source: Internet
Author: User

Self-compiled DAL three-tier code generator and dal three-tier Code Generator

(1) Create your own solution directory structure as follows:


(2) Compile the Code:

(To use a database, we recommend that you create any database)

The code for creating the configuration file App. config is as follows:

<? Xml version = "1.0"?> <Configuration> <connectionStrings> <add name = "connstr" connectionString = "Data Source = .; initial Catalog = HRMSYSDB; User ID = hrmsa; Password = Your Database Password "/> </connectionStrings> <etettings> <add key =" passwordSalt "value =" love? P3 @ 9 "/> <add key =" aaa "value =" 333 "/> </appSettings> </configuration>
The MainWindow. xaml code is as follows: (change the code in the Grid in MainWindow. xaml)

<Grid> <TextBox Height = "23" HorizontalAlignment = "Left" Margin = "16, 7, 0, 0 "Name =" txtConnStr "VerticalAlignment =" Top "Width =" 542 "/> <Button Content =" connection "Height =" 23 "HorizontalAlignment =" Left "Margin =" 564,7, 0, 0 "Name =" btnConnect "verticalignment =" Top "Width =" 41 "Click =" btnConnect_Click "/> <ComboBox Height =" 23 "HorizontalAlignment =" Left "Margin =" 16, 36, 210 "Name =" cmbTables "verticalignment =" Top "Width =" "IsEnabled =" False "/> <Button Content =" generate code "Height =" 23 "HorizontalAlignment =" left "Margin =" 244,36, 0, 0 "Name =" btnGenerateCode "VerticalAlignment =" Top "Width =" 75 "IsEnabled =" False "Click =" btnGenerateCode_Click "/> <TextBox TextWrapping =" Wrap "placement =" Auto "HorizontalScrollBarVisibility =" Auto "Height =" 483 "HorizontalAlignment =" Left "Margin =, 342 "Name =" txtModelCode "verticalignment =" Top "Width =" "IsReadOnly =" True "/> <TextBox TextWrapping =" Wrap "VerticalScrollBarVisibility =" Auto "placement =" Auto ""Height =" 483 "HorizontalAlignment =" Left "Margin =" 372,66, 494 "Name =" txtDALCode "verticalignment =" Top "Width =" "IsReadOnly =" True "/> </Grid>

The MainWindow. xaml. cs code is as follows:

Namespace MyCodeGen // here you need to change the namespace to your own, that is, you only need to paste <span style = "font-family: Arial, Helvetica, sans-serif; "> public partial class MainWindow: Window {content below </span >{/// <summary> /// MainWindow. interaction logic of xaml // </summary> public partial class MainWindow: Window {public MainWindow () {InitializeComponent ();} private DataTable ExecuteDataTable (string SQL) {using (SqlConnection conn = new SqlConnecti On (txtConnStr. text) {conn. open (); using (SqlCommand cmd = conn. createCommand () {// only obtain the schema information (column information) of the table cmd. commandText = SQL; DataSet ds = new DataSet (); SqlDataAdapter adapter = new SqlDataAdapter (cmd); adapter. fillSchema (ds, SchemaType. source); // to obtain table information, you must write the adapter. fill (ds); return ds. tables [0] ;}} private void btnConnect_Click (object sender, RoutedEventArgs e) {DataTable table; try {table = Ex EcuteDataTable (@ "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'base table'");} catch (SqlException sqlex) {MessageBox. Show ("An error occurred while connecting to the database! Error message: "+ sqlex. message); return;} string [] tables = new string [table. rows. count]; for (int I = 0; I <table. rows. count; I ++) {DataRow row = table. rows [I]; tables [I] = (string) row ["TABLE_NAME"];} cmbTables. itemsSource = tables; cmbTables. isEnabled = true; btnGenerateCode. isEnabled = true; // record the connection string to the File to avoid entering the connection string every time. // Save the connection string to string configFile = GetConfigFilePath (); File. writeAllText (confi GFile, txtConnStr. text); // do not try again unless you need to capture exceptions... catch} // For example, avoid entering a connection database string every time to encapsulate the stored code into the function private static string GetConfigFilePath () {string currenctDir = AppDomain. currentDomain. baseDirectory; string configFile = System. IO. path. combine (currenctDir, "connstr.txt"); return configFile;} private void Window_Loaded (object sender, RoutedEventArgs e) {// The connection string configFile that is saved in the folder to be loaded every time. = GetConfigFilePath (); txtConnStr. text = File. readAllText (configFile);} private void btnGenerateCode_Click (object sender, RoutedEventArgs e) {string tablename = (string) cmbTables. selectedItem; if (tablename = null) {MessageBox. show ("select the table to be generated"); return;} CreateModelCode (tablename); CreateDALCode (tablename);} private void CreateModelCode (string tablename) {DataTable table = ExecuteDataTable ("s Elect top 0 * from "+ tablename); // use stringbuilder () StringBuilder sb = new StringBuilder (); sb. append ("public class "). appendLine (tablename ). appendLine ("{"); foreach (DataColumn column in table. columns) {string columnDataType = GetDataTypeName (column); // determines whether the type can be empty sb. append (""). append ("public "). append (columnDataType ). append (""). append (column. columnName ). appendLine ("{get; set ;}");} Sb. appendLine ("}"); txtModelCode. text = sb. toString () ;}// empty type processing private static string GetDataTypeName (DataColumn column) {// If the column can be null, the column type in C # cannot be blank (Value Type ValueType) if (column. allowDBNull & column. dataType. isValueType) {return column. dataType + "? ";} Else {return column. dataType. toString () ;}// the private void CreateDALCode (string tablename) {DataTable table = ExecuteDataTable ("select top 0 * from" + tablename) of the DALcode section is generated below ); stringBuilder sb = new StringBuilder (); sb. append ("public class "). append (tablename ). appendLine ("DAL "). appendLine ("{"); // tomodel start sb. append (""). append ("private "). append (tablename ). appendLine ("ToModel (DataRow row )"). append (""). appendLine ("{"); sb. append (""). append (tablename ). appendLine ("model = new" + tablename + "();"); foreach (DataColumn column in table. columns) {// determines whether the column is allowed to be empty or not. id = (Guid) SqlHelper. fromDbValue (row ["Id"]); sb. append (""). append ("model. "). append (column. columnName ). append ("= ("). append (GetDataTypeName (column )). append (") SqlHelper. fromDbValue (row [\""). append (column. columnName ). appendLine ("\"]); ");} sb. append (""). appendLine ("return model;"); sb. appendLine ("}"); // end of tomodel // listall start sb. append ("public IEnumerable <"). append (table ). appendLine ("> ListAll ()"). appendLine ("{"); sb. append (""). append ("List <"). append (tablename ). append ("> list = new List <"). append (tablename ). appendLine ("> ();"); sb. append ("DataTable dt = SqlHelper. executeDataTable (\""). append ("select * from" + tablename ). appendLine ("\"); "); sb. appendLine ("foreach (DataRow row in dt. rows) "); sb. append (tablename ). appendLine ("model = ToModel (row);"); sb. appendLine ("list. add (model) ;}"); sb. appendLine ("}"); // The generator requires that the column name must be Id and the type must be Guid // Insert start // public void Insert (Operator op) sb. append ("public void Insert ("). append (tablename ). appendLine ("model) {"); // SqlHelper. executeNonQuery (@ "insert into T_Operator (sb. append ("SqlHelper. executeNonQuery (@\""). append ("insert "). append (tablename ). appendLine ("("); string [] colNames = GetColumnNames (table); sb. appendLine (string. join (",", colNames); string [] colParamNames = GetParamColumnNames (table); sb. append ("values ("). appendLine (string. join (",", colParamNames); sb. appendLine ("}"); // Insert ends sb. appendLine ("}"); txtDALCode. text = sb. toString ();} // returns the column name private static string [] GetColumnNames (DataTable table) {string [] colnames = new string [table. columns. count]; for (int I = 0; I <table. columns. count; I ++) {DataColumn dataCol = table. columns [I]; colnames [I] = dataCol. columnName;} return colnames;} // returns the @ column name private static string [] GetParamColumnNames (DataTable table) {string [] colnames = new string [table. columns. count]; for (int I = 0; I <table. columns. count; I ++) {DataColumn dataCol = table. columns [I]; colnames [I] = "@" + dataCol. columnName;} return colnames ;}}}

The SqlHelper. cs code is as follows: (the code in the namespace)

Namespace MyCodeGen {static class SqlHelper {// app. config File inheritance: public static readonly string connstr = ConfigurationManager. connectionStrings ["connstr"]. connectionString; // do not forget to add reference System. configuration is then parsed to the step: Right-click reference -- add reference --. NET -- find System. configuration OK. public static int ExecuteNonQuery (string SQL, params SqlParameter [] parameters) {using (SqlConnection conn = new SqlConnection (connstr) {conn. open (); using (SqlCommand cmd = conn. createCommand () {cmd. commandText = SQL; cmd. parameters. addRange (parameters); return cmd. executeNonQuery () ;}} public static object ExecuteScalar (string SQL, params SqlParameter [] parameters) {using (SqlConnection conn = new SqlConnection (connstr) {conn. open (); using (SqlCommand cmd = conn. createCommand () {cmd. commandText = SQL; cmd. parameters. addRange (parameters); return cmd. executeScalar () ;}} public static DataTable ExecuteDataTable (string SQL, params SqlParameter [] parameters) {using (SqlConnection conn = new SqlConnection (connstr) {conn. open (); using (SqlCommand cmd = conn. createCommand () {cmd. commandText = SQL; cmd. parameters. addRange (parameters); DataSet dataset = new DataSet (); SqlDataAdapter adapter = new SqlDataAdapter (cmd); adapter. fill (dataset); return dataset. tables [0] ;}} public static object FromDbValue (object value) {if (value = DBNull. value) {return null;} else {return value;} public static object ToDbValue (object value) {if (value = null) {return DBNull. value ;}else {return value ;}}}}



All the code is ready! Click Run as follows:



For a complete project, click:

Http://download.csdn.net/detail/u010870518/7837691


If you are not familiar with importing mdf to the database, refer:

Http://blog.csdn.net/xlgen157387/article/details/38844315



How to compile the Aspnet Code Generator

Asp.net itself does not have a code generator, which is developed by a third party. if you want to, you can also create your own code generator. In fact, it is a template that allows the generated code to have the same naming rules, file preparation, access mechanisms, and so on.

When code generation is used, the prototype of the transaction class, data class, and database outline is usually used according to the specific framework. We will generate these entity classes quickly and access the DAO class for data, these classes encapsulate some basic methods.

Specifically, the usage skills are based on different generators, because after all these third parties do not have a unified specification, they are all habits.

Cannot a soft code generator generate the DAL code of a stored procedure?

You need to set the primary key first.
No primary key program can be judged.

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.