(1) Create your own solution folder structure as follows:
(2) Write code:
(You can use database suggestions to create a random database.)
Create a configuration file for the app. Config code such as the following:
<?xml version= "1.0"?><configuration> <connectionStrings> <add name= "ConnStr" Connectionstring= "Data source=.; Initial Catalog=hrmsysdb; User Id=hrmsa; Password= your database Password "/> </connectionStrings> <appSettings> <add key=" PasswordSalt " value= "[email protected]"/> <add key= "AAA" value= "333"/> </appSettings> </ Configuration>
MainWindow.xaml code such as the following: (in MainWindow.xaml under the grid inside the code to change it)
<Grid> <textbox height= "horizontalalignment=" "left" margin= "16,7,0,0" name= "Txtconnstr" Verticalalignme Nt= "Top" width= "542"/> <button content= "Connection" height= "All" horizontalalignment= "left" margin= "564,7,0,0" Name= " Btnconnect "verticalalignment=" Top "width=" "click=" Btnconnect_click "/> <combobox height=" HorizontalAl Ignment= "left" margin= "16,36,0,0" name= "Cmbtables" verticalalignment= "Top" width= "All" isenabled= "False"/> < Button content= "Generate Code" height= "horizontalalignment=" "left" margin= "244,36,0,0" name= "Btngeneratecode" Verticalalignment= "Top" width= "isenabled=" False "click=" Btngeneratecode_click "/> <textbox TextWrapping=" Wrap "verticalscrollbarvisibility=" Auto "horizontalscrollbarvisibility=" Auto "height=" 483 "horizontalalignment=" Left "margin=" 16,66,0,0 "name=" Txtmodelcode "verticalalignment=" Top "width=" 342 "isreadonly=" True "/> <TextBo X textwrapping= "Wrap" verticalscrollbarvisibility= "AUto "horizontalscrollbarvisibility=" Auto "height=" 483 "horizontalalignment=" left "margin=" 372,66,0,0 "Name=" Txtdalcode "verticalalignment=" Top "width=" 494 "isreadonly=" True "/> </Grid>
MainWindow.xaml.cs code such as the following:
Namespace Mycodegen//here to change the namespace to their own is generated by the only need to paste <span style= "font-family:arial, Helvetica, Sans-serif;" >public partial class mainwindow:window{to </span>{///<summary>//MainWindow.xaml Interactive logic </summary> public partial class Mainwindow:window {public MainWindow () {in Itializecomponent (); } Private DataTable executedatatable (String sql) {using (SqlConnection conn = new SqlConnection ( Txtconnstr.text)) {Conn. Open (); using (SqlCommand cmd = conn. CreateCommand ()) {//Only get 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);//Get table information must be written adapter. Fill (DS); Return DS. Tables[0]; }}} private void Btnconnect_click (object sender, RoutedEventArgs e) {Datat Able table; try {table = executedatatable (@ "SELECT table_name from INFORMATION_SCHEMA. TABLES WHERE table_type = ' BASE TABLE '); } catch (SqlException Sqlex) {MessageBox.Show ("Connection Database Error! 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; Log the connection string to the file. Prevent users from having to enter the connection string each time//Save the connection string As String configfile = Getconfigfilepath (); File.writealltext (CONFIGFILe, Txtconnstr.text); Unless there is a need to catch an exception, do not Try...catch}//For example, avoid entering the link database string each time the saved code is encapsulated into the function private static string Getconfigfile Path () {string currenctdir = AppDomain.CurrentDomain.BaseDirectory; String configfile = System.IO.Path.Combine (Currenctdir, "connstr.txt"); return configfile; private void Window_Loaded (object sender, RoutedEventArgs e) {//To load the connection string in the existing directory each time it is loaded String configfile = Getconfigfilepath (); Txtconnstr.text = File.readalltext (configfile); private void Btngeneratecode_click (object sender, RoutedEventArgs e) {string tablename = (stri NG) Cmbtables.selecteditem; if (tablename = = null) {MessageBox.Show ("Please select the table to generate"); Return } createmodelcode (tablename); Createdalcode (tablename); } private void Createmodelcode (string tablename) {DataTable table = executedatatable ("SELECT top 0 * from" + tablename); Use StringBuilder () StringBuilder sb = new StringBuilder () when a large number of string concatenation is used; Sb. Append ("public class"). Appendline (tablename). Appendline ("{"); foreach (DataColumn column in table. Columns) {String columndatatype = getdatatypename (column);//Infer whether the type can be null sb. Append (""). Append ("public"). Append (Columndatatype). Append (""). Append (column. ColumnName). Appendline ("{get;set;}"); } sb. Appendline ("}"); Txtmodelcode.text = sb. ToString (); }//Make nullable type processing private static string Getdatatypename (DataColumn column) {//Assuming the columns agree to be null. And the types listed in C # are non-nullable (value type ValueType) if (column. AllowDBNull && column. Datatype.isvaluetype) {return column. DataType + "?"; } else {return column. Datatype.tostring (); }}//Below is the build Dalcode section private void Createdalcode (string tablename) {DataTable table = Executedatatable ("SELECT top 0 * from" + tablename); 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) {//regardless of whether the column agrees to be empty, it is inferred that DBNull processing (easy)//model. 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 ("}"); The end of the Tomodel//listall begins with 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 an ID, and the type must be a GUID//insert start//public void Insert (OperatorOP) sb. Append ("public void Insert ("). Append (tablename). Appendline ("model") {"); Sqlhelper.executenonquery (@ "INSERT into T_operator (sb.) Append ("Sqlhelper.executenonquery (@\"). Append ("INSERT into"). 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 End SB. Appendline ("}"); Txtdalcode.text = sb. ToString (); }//returns the column name as an array 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 as an array private static string[] getparamcolumnnames (DataTable table) {string[] col names = 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; } }}
SqlHelper.cs code such as the following: (the code inside the namespace)
namespace mycodegen{static class SqlHelper {//app.config file inheritance: public static readonly string CONNSTR = configurationmanager.connectionstrings["ConnStr"]. ConnectionString; Don't forget to add the reference system.configuration and then resolve to step: Right-click on the reference-add reference--. net--Find system.configuration OK can public static int ExecuteNonQuery (String sql, params sqlparameter[] pa Rameters) {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[] param eters) {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 right, all the code is good! Click Perform effects such as the following:
For a complete project, please click here:
http://download.csdn.net/detail/u010870518/7837691
Suppose you are unfamiliar with importing a database MDF:
http://blog.csdn.net/xlgen157387/article/details/38844315
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
I've written the DAL layer code generator