1 原理:
利用 SqlDataReader .GetSchemaTable获取列元数据,然后根据列的元数据生成需要的实体。本程序主要用到了以下三个字段,SchemaTable的其它字段见MSDN.
名称 |
说明 |
ColumnName |
列的名称;它可能不唯一。如果无法确定该名称,则返回 null 值。此名称始终反映最近对当前视图或命令文本中的列进行的重命名。 |
DataType |
映射到列的 .NET Framework 类型。 |
AllowDBNull |
如果使用者可以将该列设置为 null 值,或者如果提供程序不能确定使用者是否可以将该列设置为 null 值,则设置该值。否则,不设置该值。即使列无法设置为 null 值,它仍可能包含 null 值。 |
2实现
(1) 表结构
(2) 生成表格的脚本
USE [BPMDB]
GO
/****** 对象: Table [dbo].[PW_User] 脚本日期: 09/03/2011 13:13:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PW_User](
[ID] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_PW_User_ID]
DEFAULT (newid()),
[userNo] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
[password] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NOT NULL,
[lastName] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NOT NULL,
[firstName] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NULL,
[alias] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NULL,
[sex] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NULL,
[birthDate] [datetime] NULL,
[phone] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NULL,
[email] [nvarchar](max) COLLATE Chinese_PRC_CI_AS NULL,
[showRule] [nvarchar](255) COLLATE Chinese_PRC_CI_AS NULL,
[isFreeze] [int] NULL,
CONSTRAINT [PK_PW_User_Id] PRIMARY KEY NONCLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
(3) 代码
/*******************************************************************
* * Copyright (C) hbb0b0
* * All rights reserved.
* *
* Author: HBB0b0 (hbb0b0@163.com)
* Create Date:2011/9/3 13:00:59
* Description:简单的数据库实体生成工具
* *
* * Date Author Description
* *******************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Configuration;
namespace HBB0b0
{
class Program
{
static void Main(string[] args)
{
using (SqlConnection myConnection = new
SqlConnection(ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString))
{
myConnection.Close();
myConnection.Open();
DataTable dt = null;
string tableName = "PW_User";
dt = GetTableSchema(myConnection, tableName);
WriteClassEntity(dt, tableName);
}
Console.Read();
}
/// <summary>
/// 获取指定表的架构
/// </summary>
/// <param name="connection"></param>
/// <param name="tableName"></param>
/// <returns></returns>
private static DataTable GetTableSchema(SqlConnection connection, string
tableName)
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("select top (1) * from {0} with(nolock) ",
tableName);
DataTable dt = null;
// using (SqlDataReader read = cmd.ExecuteReader())
{
SqlDataReader read = cmd.ExecuteReader();
dt = read.GetSchemaTable();
}
return dt;
}
}
/// <summary>
/// 生成表对应的实体
/// </summary>
/// <param name="dtSchema"></param>
/// <param name="tableName"></param>
private static void WriteClassEntity(System.Data.DataTable dtSchema, string
tableName)
{
StringBuilder sb = new StringBuilder();
sb.Append("[Serializable]");
sb.AppendLine();
sb.AppendFormat("public class {0}Entity", tableName);
sb.AppendLine();
sb.AppendLine("{");
foreach (System.Data.DataRow row in dtSchema.Rows)
{
//列名称
DataColumn nameCol =
dtSchema.Columns[dtSchema.Columns.IndexOf("ColumnName")];
//类型
DataColumn typeCol =
dtSchema.Columns[dtSchema.Columns.IndexOf("DataType")];
//是否为空
DataColumn allowDBNullCol =
dtSchema.Columns[dtSchema.Columns.IndexOf("AllowDBNull")];
string symbolCanNull = "";
if (Boolean.Parse(row[allowDBNullCol].ToString()) &&
Type.GetType(row[typeCol].ToString()).IsValueType)
{
symbolCanNull = "?";
}
string info = string.Format("public {0}{1} {2} {3} get; set; {4}",
row[typeCol].ToString(),
symbolCanNull,
row[nameCol].ToString(),
"{", "}");
sb.AppendLine(info);
}
sb.AppendLine("}");
//Trace.Listeners.Remove("myListener");
Console.WriteLine(sb.ToString());
//Trace.Write(sb.ToString());
//Trace.Flush();
}
}
}