[個人小工具] SSMS資料庫 轉成C# class程式碼

  • 425
  • 0

因為最近不太愛用EF了,比較偏好dapper

但有時候需要快速產生一個相同結構的class模型

因此寫了小工具

Step 1.  透過SSMS copy這三欄

Step 2.  將複製的內容 貼到 postman 上

Step 3.  postman response 成功得到結果 可以copy貼到你的程式碼上

 

 

程式碼如下,總之就是根據換行符號、分解出每一行

然後依序解析出 DB欄位對應C#哪一種型別的欄位 產生出一個class提供Copy

[Route("DB_to_Class/{tableName}")]
[HttpPost]
public object ConvertDataSchema_To_CSharpClass([FromUri]string tableName)
{
	var requestBody = GetBodyStringFromInputstream(System.Web.HttpContext.Current.Request.InputStream);

	if (string.IsNullOrWhiteSpace(requestBody))
		return "no input text";

	List<string> lines = requestBody.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Where(x=> !string.IsNullOrWhiteSpace(x)).ToList();

	int totalColumns = 0;
	string yourClassText = $"public class {tableName}Enity " + Environment.NewLine;
	yourClassText += "{" + Environment.NewLine;


	foreach (var eachDBColumn in lines)
	{
		List<string> split = eachDBColumn.Split('\t').Where(x=> !string.IsNullOrWhiteSpace(x)).ToList();

		if (split.Count() != 3)
			continue;

		var columName = split[0];
		var columType = split[1].Trim();
		var isNullChecked = split[2].Trim();

		var csharpType = "string";

		if (columType == "int")
			csharpType = "int";
		if (columType == "bit")
			csharpType = "bool";
		else if (columType == "bigint")
			csharpType = "long";
		else if (columType == "tinyint")
			csharpType = "byte";
		else if (columType == "smallint")
			csharpType = "short";
		else if (columType == "float")
			csharpType = "float";        
		else if (columType == "datetime")
			csharpType = "DateTime";
		else if (columType == "date")
			csharpType = "DateTime";
		else if (columType == "uniqueidentifier")
			csharpType = "Guid";                
		else if (columType.Contains("decimal"))
			csharpType = "decimal";
		else if (columType.Contains("char"))
			csharpType = "string";

		string get_set_text = "{get;set;}";
		string isNullableText = "";

		if(csharpType != "string")
		{
			if(isNullChecked == "Checked")
			{
				isNullableText = "?";
			}
		}
		

		yourClassText += $" public {csharpType}{isNullableText} {columName} {get_set_text}" + Environment.NewLine;
		totalColumns++;
	}

	yourClassText += "}" + Environment.NewLine;

	var response = new HttpResponseMessage();
	response.Content = new StringContent(yourClassText);
	response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
	return response;
}



public static string GetBodyStringFromInputstream(Stream inputStream)
{
	string requestBody = string.Empty;

	using (var stream = inputStream)
	using (var reader = new StreamReader(stream))
	{
		requestBody = reader.ReadToEnd();
	}

	return requestBody;
}