偶爾翻到以前寫的小玩意,數據表實體類生成!只寫了Access資料庫,等將來有時間試著看看寫一個相容市面主流資料庫的! 代碼如下: static class Program { /// <summary> /// 應用程式的主入口點。 /// </summary> [STAThread] static ...
偶爾翻到以前寫的小玩意,數據表實體類生成!只寫了Access資料庫,等將來有時間試著看看寫一個相容市面主流資料庫的!
代碼如下:
static class Program
{
/// <summary>
/// 應用程式的主入口點。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
下麵是主窗體代碼:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region 全部變數定義
bool Canmove = false;
Point Pf;
// string ConnectionString = "";
#endregion
void WriteLog(string logstr)
{
textBox2.Text += logstr+"\r\n";
}
#region 測試資料庫是否能連上
void TestConnection(string str)
{
using (OleDbConnection con = new OleDbConnection(str))
{
textBox2.ResetText();
try
{
WriteLog("嘗試打開資料庫鏈接......");
con.Open();
WriteLog("資料庫鏈接測試成功!");
}
catch (Exception ex)
{
WriteLog("資料庫鏈接測試失敗:"+ex.Message);
}
finally
{
WriteLog("關閉資料庫鏈接....");
con.Close();
}
}
}
#endregion
#region 取得資料庫的表名
string[] GetTableNames(string str)
{
using (OleDbConnection con = new OleDbConnection(str))
{
DataTable dt = new DataTable();
try
{
con.Open();
WriteLog("開始從資料庫獲得所有表名!");
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "table" });
int n = dt.Rows.Count;
string[] strTable = new string[n];
int m = dt.Columns.IndexOf("TABLE_NAME");
for (int i = 0; i < n; i++)
{
DataRow m_DataRow = dt.Rows[i];
strTable[i] = m_DataRow.ItemArray.GetValue(m).ToString();
}
WriteLog("成功取得所有表名!");
return strTable;
}
catch (Exception ex)
{
WriteLog("獲取表名出錯:"+ex.Message);
return null;
}
finally
{
con.Close();
dt.Dispose();
}
}
}
#endregion
#region 根據表名取得表中每個欄位及對應數據類型
Dictionary<string ,string > GetCoulmNams(string constr,string TableName)
{
using (OleDbConnection con = new OleDbConnection(constr))
{
DataTable dt = new DataTable();
try
{
WriteLog("根據表名稱獲取所有欄位及其對應的數據類型!");
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, TableName, null });
// dataGridView1.DataSource = dt;
int n = dt.Rows.Count;
Dictionary<string, string> CoulnmsInfo = new Dictionary<string, string>();
int m = dt.Columns.IndexOf("COLUMN_NAME");
int j = dt.Columns.IndexOf("DATA_TYPE");
for ( int i = 0; i < n; i++)
{
DataRow m_DataRow = dt.Rows[i];
CoulnmsInfo.Add(m_DataRow.ItemArray.GetValue(m).ToString(),GetType((int)m_DataRow.ItemArray.GetValue(j)));
WriteLog("獲取欄位" + m_DataRow.ItemArray.GetValue(m).ToString() + "的類型碼成功!");
}
return CoulnmsInfo;
}
catch (Exception ex)
{
WriteLog("獲取欄位類型出錯:"+ex.Message);
return null;
}
finally
{
con.Close();
dt.Dispose();
}
}
}
#endregion
#region 判斷欄位是否為主鍵
bool IsprimaryKeys(string tbname,string Name)
{
OleDbConnection connection = new OleDbConnection(textBox1.Text.Trim());
connection.Open();
// DataTable schemaColumns = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new string[] { null, null,tbname, null });
DataTable primaryKeys = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, new string[] { null, null, tbname });
connection.Close();
int j = -1;
foreach (DataRow row in primaryKeys.Rows)
{
string fname=row["COLUMN_NAME"].ToString();
if (fname == Name)
{
j++;
}
}
if (j>=0)
{ return true; }
else
{
return false;
}
}
#endregion
#region 資料庫類型與C#中類型轉換
string GetType(int num)
{
switch (num)
{
case 2:
return "Int16";
case 3:
return "int";
case 4:
return "Single";
case 5:
return "Double";
case 6:
case 131:
return "decimal";
case 7:
return "DateTime";
case 11:
return "bool";
case 18:
return "byte";
case 130:
return "string";
case 128:
return "Binary";
case 129:
return "char";
case 0:
case 8:
case 9:
case 10:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 19:
case 20:
case 21:
case 64:
case 72:
case 132:
case 133:
case 134:
case 135:
case 136:
case 138:
case 139:
case 200:
case 203:
case 204:
case 205:
return "";
default: return null ;
}
}
#endregion
#region 寫文件
void WriteFile(string NameSpaces,string FileName1,string FileName2,IDbConnection dbconnect)
{
if (File.Exists(FileName1 + ".cs"))
{
File.Delete(FileName1 + ".cs");
}
if (File.Exists(FileName2 + ".cs"))
{
File.Delete(FileName2 + ".cs");
}
WriteLog("創建文件!");
FileInfo f = new FileInfo(FileName1 + ".cs");
FileInfo f1=new FileInfo (FileName2 + ".cs");
StreamWriter sw1 = f1.AppendText();
StreamWriter sw = f.AppendText();
try
{
WriteLog("一.寫文件頭:");
WriteLog("1.寫DB類文件頭!");
sw1.WriteLine("using System.Data;");
sw1.WriteLine("using System.Data.Linq;");
sw1.WriteLine("using System.Data.OleDb;");
sw1.WriteLine("using System.Diagnostics;");
sw1.WriteLine("namespace "+NameSpaces );
sw1.WriteLine("{");
sw1.WriteLine("public class DB");
sw1.WriteLine("{");
sw1.WriteLine("DataContext dc;");
WriteLog("2.寫實體類文件頭!");
sw.WriteLine("using System.Data.Linq.Mapping;");
sw.WriteLine("namespace\t"+NameSpaces );
sw.WriteLine ("{");
//一下根據表生產對應的類,根據表中的欄位生產對應屬性;
string[] tables = GetTableNames(textBox1.Text.Trim());
int l = 1;
WriteLog("二.寫文件內容:");
foreach (string str in tables)
{
WriteLog("開始寫第" + l + "張表("+str+")的實體類!");
//根據表明寫類名
sw.WriteLine("[Table (Name=\""+str+"\")]");
sw.WriteLine("public class " + str);
sw.WriteLine("{");
Dictionary<string, string> di = GetCoulmNams(textBox1.Text, str);
foreach (KeyValuePair<string, string> value in di)
{
WriteLog("開始寫欄位:" + value.Key );
if (IsprimaryKeys(str, value.Key) == true)
{
sw.WriteLine("[Column(IsPrimaryKey =true)]");
}
else
{
sw.WriteLine("[Column]");
}
sw.WriteLine("public " + value.Value + " " + value.Key + "{get;set;}");
}
sw.WriteLine("}");
WriteLog("寫第" + l + "張表的申明!");
sw1.WriteLine("public Table<" + str + ">" + str + ";");
l++;
}
WriteLog("寫DB類的初始化方法!");
sw1.WriteLine("public DB(IDbConnection con) ");
sw1.WriteLine("{");
sw1.WriteLine("dc = new DataContext(con);");
int n=1;
foreach(string str in tables)
{
WriteLog("建立第" + n + "張表的Object對象!");
sw1.WriteLine(str +"=dc.GetTable<"+str+">();");
n++;
}
WriteLog("三.寫文件尾:");
sw.WriteLine("}");
sw1.WriteLine("}");
sw1.WriteLine("}");
sw1.WriteLine("}");
WriteLog("生成文件成功!");
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "explorer";
psi.Arguments = "/e,/select," + Application.StartupPath + FileName1+".cs";
Process.Start(psi);
}
catch (Exception ex)
{
WriteLog("生成文件發生錯誤:"+ex.Message);
}
finally
{
sw.Close();
sw1.Close();
}
}
#endregion
#region 測試鏈接按鈕單擊事件
private void button1_Click(object sender, EventArgs e)
{
WriteLog("測試鏈接按鈕單擊");
TestConnection(textBox1.Text.Trim());
}
#endregion
#region 生成.cs文件按鈕單擊事件
private void button2_Click(object sender, EventArgs e)
{
textBox2.ResetText();
WriteLog("生成.cs文件按鈕單擊");
string namespaces = Interaction.InputBox("請輸入命名空間!", "輸入命名空間", "gaofajin",Control.MousePosition.X -200,Control.MousePosition.Y-100);
if (namespaces.Length == 0)
{
WriteLog("沒有輸入命名空間,生成文件操作無法繼續!");
return;
}
string filename1 = Interaction.InputBox("請輸入實體類文件名稱!", "輸入文件名", "gaofajinmodel", Control.MousePosition.X-200, Control.MousePosition.Y-100);
if (namespaces.Length == 0)
{
WriteLog("沒有輸入實體類文件名!生成文件操作無法繼續!");
return;
}
string filename2 = Interaction.InputBox("請輸入DB類文件名稱!", "輸入文件名", "gaofajinDB", Control.MousePosition.X -200, Control.MousePosition.Y-100);
if (namespaces.Length == 0)
{
WriteLog("沒有輸入DB類文件名!生成文件操作無法繼續!");
return;
}
IDbConnection c = new OleDbConnection(textBox1.Text.Trim());
WriteFile(namespaces,filename1,filename2,c);
}
#endregion
#region 退出程式按鈕單機時間
private void button3_Click(object sender, EventArgs e)
{
Close();
}
#endregion
#region 使無邊框的窗體可以拖動
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (Canmove == true && e.Button == MouseButtons.Left)
{
Point p = Control.MousePosition;
p.Offset(Pf);
Location = p;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
Canmove = false;
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Canmove = true;
Pf = new Point(-e.X, -e.Y);
}
}
#endregion
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
WriteLog("程式正在被關閉!");
if (DialogResult.OK != MessageBox.Show("確定退出程式嗎?", "退出程式", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
{
e.Cancel = true;
}
else { e.Cancel = false; }
}
private void button4_Click(object sender, EventArgs e)
{
textBox1.Text = ShowConnectDialog();
}
string ShowConnectDialog()
{
string ConnectionString = string.Empty;
DataConnectionDialog dcd = new DataConnectionDialog();
dcd.DataSources.Add(DataSource.AccessDataSource);
dcd.DataSources.Add(DataSource.OdbcDataSource);
dcd.DataSources.Add(DataSource.OracleDataSource);
dcd.DataSources.Add(DataSource.SqlDataSource);
dcd.DataSources.Add(DataSource.SqlFileDataSource);
if (DialogResult.OK ==DataConnectionDialog.Show(dcd))
{
ConnectionString = dcd.ConnectionString;
}
return ConnectionString;
}
}