MSSQL数据库表,批量转c#实体类 ,我知道网上有现成的,可是我就想自己写个来玩玩
这个工具的关键点,在于获取到表的所有字段名和类型,然后就是拼接字符串的事了
直接上代码
首先就是获取所有数据库名,数据库下的所有表名和表里的所有字段,具体怎么获取,拿sql到数据库里跑一下就清楚了
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace DataTableToEntityClass
{
public class DAL:IDAL
{
/// <summary>
/// 获取服务器上所有数据库名
/// </summary>
/// <param name="conStr"></param>
/// <returns></returns>
public List<TempModel> GetDataBaseList(string conStr)
{
List<TempModel> result = new List<TempModel>();
string sql = "Select Name From Master..SysDatabases order By Name";
DataSet ds = SqlHelper.sqlSelectDS(conStr, CommandType.Text, sql);
foreach(DataRow row in ds.Tables[0].Rows)
{
result.Add(new TempModel { Name = row["Name"].DBValueToTypeValue<string>() ?? "", Type = "DataBase" });
}
return result;
}
/// <summary>
/// 获取指定数据库的所有表名
/// </summary>
/// <param name="conStr"></param>
/// <returns></returns>
public List<TempModel> GetTableList(string conStr)
{
List<TempModel> result = new List<TempModel>();
string sql = $"Select Name From sysobjects Where XType='U' order By Name";
DataSet ds = SqlHelper.sqlSelectDS(conStr, CommandType.Text, sql);
foreach (DataRow row in ds.Tables[0].Rows)
{
result.Add(new TempModel { Name = row["Name"].DBValueToTypeValue<string>() ?? "", Type = "Table" });
}
return resul