NHibernate生成实体类、xml映射文件

最近工作电脑装完win10后,之前使用的codeSmith安装不了,索性自己写一个。

界面比较简单,如下图:

NHibernate生成实体类、xml映射文件

第一行为Oracle数据库的连接字符串。连接成功后,填充表到第4行的下拉列表中。

第二行为实体类命名空间。

第三行为保存生成类、xml文件选择文件夹。

 private void btnConnect_Click(object sender, RoutedEventArgs e)
{
try
{
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = txtConnStr.Text; using (OracleCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select distinct table_name from user_tables order by table_name"; DataTable dt = new DataTable(); OracleDataAdapter adapter = new OracleDataAdapter();
adapter.SelectCommand = cmd; adapter.Fill(dt); cbTables.DisplayMemberPath = "TABLE_NAME";
cbTables.SelectedValuePath = "TABLE_NAME";
cbTables.ItemsSource = dt.DefaultView; } MessageBoxShow("连接成功!"); }
}
catch
{
MessageBoxShow("连接失败!");
}
}

测试连接按钮事件

 private void btnChoseDirectory_Click(object sender, RoutedEventArgs e)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
DialogResult dialogResult = folderDialog.ShowDialog(); if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
labDirectoryPath.Content = folderDialog.SelectedPath.Trim();
}
}

选择文件夹按钮事件

 private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtEntityClassNamespace.Text.Trim()))
{
MessageBoxShow("请输入实体命名空间名称!");
txtEntityClassNamespace.Focus();
return;
}
if (labDirectoryPath.Content == null)
{
MessageBoxShow("请选择文件夹保存生成文件!");
btnChoseDirectory.Focus();
return;
}
if (cbTables.SelectedValue == null)
{
MessageBoxShow("请选择表名!");
return;
} DataTable dt = GetTableSchemaByTableName(); GenerateClass(dt); GenerateMappingXml(dt); MessageBoxShow("生成成功!");
} private string OracleTypeToCSType(string oracleType)
{
string csType = string.Empty; switch (oracleType.ToUpper())
{
case "NVARCHAR2":
case "VARCHAR2":
case "CHAR":
csType = "string";
break;
case "LONG":
csType = "long";
break;
case "NUMBER":
csType = "int";
break;
case "DATE":
csType = "datetime";
break;
} return csType;
} private DataTable GetTableSchemaByTableName()
{
string selectSQL = @"select t1.COLUMN_NAME,t1.data_type,t1.data_length,t1.nullable,t2.comments,
replace(initcap(t1.TABLE_NAME),'_','') className
from user_tab_columns t1 left
join user_col_comments t2
on t1.TABLE_NAME = t2.table_name and t1.COLUMN_NAME = t2.column_name
where t1.table_name = :table_name
order by to_number(t1.column_id)"; DataTable dt = new DataTable();
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = txtConnStr.Text; using (OracleCommand cmd = conn.CreateCommand())
{
cmd.CommandText = selectSQL;
cmd.Parameters.Add(new OracleParameter(":table_name", cbTables.SelectedValue)); OracleDataAdapter adapter = new OracleDataAdapter();
adapter.SelectCommand = cmd; adapter.Fill(dt);
}
} return dt;
} private void GenerateClass(DataTable dt)
{
string entityClassNamespace = txtEntityClassNamespace.Text;
if (dt.Rows.Count > )
{
string className = dt.Rows[]["className"].ToString(); using (FileStream csStream = new FileStream(System.IO.Path.Combine(labDirectoryPath.Content.ToString(), className + ".cs"), FileMode.Create, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(csStream, Encoding.Default))
{
writer.WriteLine(string.Format("namespace {0}", entityClassNamespace)); writer.WriteLine("{");
writer.WriteLine(string.Format(@" public class {0} : BaseModel
{{", className));
for (int i = ; i < dt.Rows.Count; i++)
{
writer.WriteLine(string.Format(@" /// <summary>
/// {0}
/// </summary>", dt.Rows[i]["comments"].ToString()));
writer.WriteLine(string.Format(" public virtual {0} {1} {{ set; get; }}",
OracleTypeToCSType(dt.Rows[i]["data_type"].ToString()),
dt.Rows[i]["COLUMN_NAME"].ToString()));
writer.WriteLine();
}
writer.WriteLine(" }");
writer.WriteLine("}");
}
} }
} private void GenerateMappingXml(DataTable dt)
{
string entityClassNamespace = txtEntityClassNamespace.Text;
if (dt.Rows.Count > )
{
string className = dt.Rows[]["className"].ToString(); XNamespace xmlns = "urn:nhibernate-mapping-2.2"; var xDoc = new XDocument(new XElement(xmlns + "hibernate-mapping",
new XElement(xmlns + "class",
new XAttribute("name", string.Format("{0}.{1},{0}", entityClassNamespace, className)),
new XAttribute("table", cbTables.SelectedValue),
new XAttribute("lazy", "true"),
new XElement(xmlns + "id",
new XAttribute("column", "ID"),
new XAttribute("name", "ID"),
new XElement(xmlns + "generator",
new XAttribute("class", "sequence"),
new XElement(xmlns + "param",
new XAttribute("name", "sequence"),
new XText(string.Format("SEQ_{0}", cbTables.SelectedValue))
)))))); XElement _class = xDoc.Root.Element(xmlns + "class"); for (int i = ; i < dt.Rows.Count; i++)
{
string columnName = dt.Rows[i]["COLUMN_NAME"].ToString(); XElement property = new XElement(xmlns + "property");
property.SetAttributeValue("name", columnName);
property.SetAttributeValue("column", columnName); _class.Add(property);
} xDoc.Save(System.IO.Path.Combine(labDirectoryPath.Content.ToString(), className + ".hbm.xml"));
}
}

生成按钮事件

总结:

  1. 使用user_tables系统表查询用户所有表
  2. 使用user_tab_columns查询表的所有列
  3. 使用user_col_comments查询表的备注信息
  4. 使用文件流生成实体类,使用Linq to xml生成*.hbm.xml文件
上一篇:eclipse逆向生成实体类


下一篇:winform 获取文件夹的名称 分类: WinForm 2014-08-04 15:50 242人阅读 评论(0) 收藏