(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> <appsettings> <add key =" passwordsalt "value =" [email protected] "/> <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. // file. writealltext ("connstr.txt", txtconnstr. text); // save as your own working directory by default // string Currenctdir = appdomain. currentdomain. basedirectory // get the folder of the current program, which is the most stable // string configfile = currenctdir + "connstr.txt"; // Save the connection string to string configfile = getconfigfilepath (); file. writealltext (configfile, 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 Co Nfigfile = system. io. path. combine (currenctdir, "connstr.txt"); Return configfile;} private void window_loaded (Object sender, routedeventargs E) {// The connection string configfile = getconfigfilepath (); txtconnstr. TEXT = file. readalltext (configfile);} private void btngeneratecode_click (Object sender, routedeventargs e) {string tablename = (string) cmbtables. selecteditem; If (tablen Ame = NULL) {MessageBox. show ("select the table to be generated"); return;} createmodelcode (tablename); createdalcode (tablename);} private void createmodelcode (string tablename) {// bool B = true; // bool and system. boolean is the same thing // system. boolean b1 = true; // CTS // system. string S1 = ""; // string S2 = ""; datatable table = executedatatable ("select top 0 * from" + tablename ); // use stringbuilder () stringbuilder Sb when splicing a large number of strings = 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 ();} // process the private stat with an empty type IC string getdatatypename (datacolumn column) {// If the column can be null and the type of the column 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 // start of listall // public ienumerable <Department> listall () Sb. append ("Public ienumerable <"). append (table ). appendline ("> listall ()"). appendline ("{"); // list <Department> List = new list <Department> (); sb. append (""). append ("list <"). append (tablename ). append ("> List = new list <"). append (tablename ). appendline ("> ();"); // datatable dt = sqlhelper. executedatatable // ("select * From t_department"); sb. append ("datatable dt = sqlhelper. executedatatable (\""). append ("select * from" + tablename ). appendline ("\"); "); sb. appendline ("foreach (datarow row in DT. rows) "); // Department dept = tomodel (ROW); sb. append (tablename ). appendline ("model = tomodel (ROW);"); // list. add (model); sb. appendline ("list. add (model) ;}"); sb. appendline ("}"); // listall end // getbyid (); // deletebyid (); // The Builder requires that the column name be ID, 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)
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 <PRE name = "code" class = "CSHARP"> <span style = "white-space: pre"> </span> // configurationmanager: right-click reference -- add reference --. net -- find <span style = "font-family: Arial, Helvetica, sans-serif;"> system. configuration OK </span>
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 = new dataset (); sqldataadapter adapter = new sqldataadapter (CMD); adapter. fill (Dataset); Return dataset. tables [0] ;}/// try // {//} // catch // {// DT able dt = new datatable (); // return DT; //} 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
Self-compiled Dal three-layer Code Generator