Hand in hand to teach you to write a visual code generator based on sqlsugar 4 (generate entity, take SqlServer as an example, the source code is attached at the end of the article)

Keywords: ASP.NET Database JSON SQL Javascript

In the development process, it is inevitable to create entity classes. Tables with fewer fields can be written manually. However, if more fields are created manually, it is a waste of time. If a table has more than 100 fields, handwriting is not realistic.

At this time, we will use some tools, such as dynamic soft code generator, code generator of ORM framework, etc.

Let's build a wheel by ourselves based on SqlSugar (ORM framework), taking SqlServer as an example. Let's take a look at the effect of the finished product,

 

Use process:

Configure the database link, click [link database] to get the database name on the specified server, click the database name, and dynamically get all tables under the database,

Click the data table, if the generated entity is automatically obtained, if not, click generate entity to automatically generate the display, and directly copy to use.

Note: server=192.168.0.154 if it is not configured locally, server =. Can be used directly.

 

 

Development environment:

Compiler: Visual Studio 2017

Running environment: windows7 x64

Database: SqlServer2012

 

Code implementation steps:

1, Create a ASP.NET Web application, named GenerateEntity

 

 

 

 

 

 

2, Apply SqlSugar dynamic link library

 

 

 

3, Write code

There are front-end and back-end, front-end page display and back-end back-end logic (Note: since we are code display, we do not engage in three-tier architecture and factory mode, which are directly completed in the controller, and students who need to change according to the needs of the project)

Internal implementation logic:

  • Configure the database link on the page, click the [link database] button to obtain all database names of the specified database and display them on the left;
  • Click the database name on the left to dynamically obtain all the tables under the specified database and display them;
  • Click the table name, the generated entity will be displayed, and if not, click generate entity to generate (support the generation of single table and database table);

Here I post the code directly, and directly copy it to use:

Front end html page

@{
    ViewBag.Title = "Home Page";
}

<script src="~/Scripts/jquery-3.3.1.js"></script>

<div style="margin-top:10px;font-family:'Microsoft YaHei';font-size:18px; ">
    <div style="height:100px;width:100%;border:1px solid gray;padding:10px">
        <div>
            <span>Linked database:</span>
            <input style="width:800px;max-width:800px;" id="Link" value="server=192.168.0.154;uid=sa;pwd=jutong!%(!%(" />
            <a href="javascript:void(0)" onclick="LinkServer()">Linked database</a>
        </div>
        <div style="margin-top:10px">
            <span>Database name:</span>
            <input style="color:red;font-weight:600" id="ServerName" />

            <span>Table name:</span>
            <input style="color:red;font-weight:600" id="TableName" />

            <span>Build type:</span>
            <select id="type">
                <option value="0">Generate a single table</option>
                <option value="1">Generate all tables</option>
            </select>
            <a  href="javascript:void(0)" onclick="GenerateEntity()" style="margin-left:20px;font-weight:600;">Generate entity</a>
            <br />

        </div>
    </div>
    <div style="height:720px;width:100%;">
        <div style="height:100%;width:40%;float:left; border:1px solid gray;font-size:20px">

            <div id="leftserver" style="float:left;border:1px solid gray;height:100%;width:40%;padding:10px;overflow: auto;">

            </div>
            <div id="lefttable" style="float:left;border:1px solid gray;height:100%;width:60%;padding:10px;overflow: auto;">

            </div>
        </div>
        <div  style="height:100%;width:60%;float:left;border:1px solid gray;overflow: auto;">
            <textarea style="width:100%;height:100%;max-width:10000px" id="righttable"></textarea>
        </div>
    </div>
</div>

<script type="text/javascript">

    //Linked database
    function LinkServer() {
        $.ajax({
            url: "/Home/LinkServer",
            data: { Link: $("#Link").val() },
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                if (data.res) {
                    if (data.info != "") {
                        $("#leftserver").html("");
                        var leftserver = "<span>Database name</span><hr />";
                        var info = eval("(" + data.info + ")");
                        for (var i = 0; i < info.length; i++) {
                            leftserver += "<a onclick=\"leftserver('" + info[i].Name + "')\">" + info[i].Name + "</a><br />";
                        }

                        $("#leftserver").html(leftserver);
                    }
                }
                else {
                    alert(data.msg);
                }
            }
        });
    }

    //Query the table of the specified database
    function leftserver(Name) {
        $("#ServerName").val(Name)
        $.ajax({
            url: "/Home/GetTable",
            data: { Link: $("#Link").val(), Name: Name },
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                if (data.res) {
                    if (data.info != "") {
                        $("#lefttable").html("");
                        var lefttable = "<span>Table name</span><hr />";
                        var info = eval("(" + data.info + ")");
                        for (var i = 0; i < info.length; i++) {
                            lefttable += "<a onclick=\"lefttable('" + info[i].Name + "')\">" + info[i].Name + "</a><br />";
                        }

                        $("#lefttable").html(lefttable);
                    }
                }
                else {
                    alert(data.msg);
                }
            }
        });
    }

    //Query the table of the specified database
    function lefttable(Name) {
        $("#TableName").val(Name);
        $.ajax({
            url: "/Home/GetGenerateEntity",
            data: { TableName: Name },
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                if (data.res) {
                    document.getElementById("righttable").innerHTML = data.info;
                }
                else {
                    alert(data.msg);
                }
            }
        });
    }

    //Generate entity
    function GenerateEntity() {

        $.ajax({
            url: "/Home/GenerateEntity",
            data: {
                Link: $("#Link").val(),
                Name: $("#ServerName").val(),
                TableName: $("#TableName").val(),
                type: $("#type").val()
            },
            type: "POST",
            async: false,
            dataType: "json",
            success: function (data) {
                if (data.res) {
                    document.getElementById("righttable").innerHTML = data.info;
                }
                else {
                    alert(data.msg);
                }
            }
        });
    }

</script>

 

Back end controller data

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace GenerateEntity.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }


     
        //Linked database
        public JsonResult LinkServer(string Link)
        {
            ResultInfo result = new ResultInfo();
            try
            {
                //Configure database connection
                SqlSugarClient db = new SqlSugarClient(
                                    new ConnectionConfig()
                                    {
                                        ConnectionString = ""+ Link + ";database=master",
                                        DbType = DbType.SqlServer,//Set database type
                                    IsAutoCloseConnection = true,//Automatically release the data service. If there is a transaction, release it after the end of the transaction
                                    InitKeyType = InitKeyType.Attribute //Read primary key auto increment column information from entity properties
                                });
                string sql = @"SELECT top 100000 Name FROM Master..SysDatabases ORDER BY Name";  //Query all linked database names
                var strList = db.SqlQueryable<databaseName>(sql).ToList();
                result.info = Newtonsoft.Json.JsonConvert.SerializeObject(strList);
                result.res = true;
                result.msg = "Link succeeded!";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //Query all tables by database name
        public JsonResult GetTable(string Link,string Name)
        {

            ResultInfo result = new ResultInfo();
            try
            {
                //Configure database connection
                SqlSugarClient db = new SqlSugarClient(
                                    new ConnectionConfig()
                                    {
                                        ConnectionString = "" + Link + ";database="+ Name + "",
                                        DbType = DbType.SqlServer,//Set database type
                                        IsAutoCloseConnection = true,//Automatically release the data service. If there is a transaction, release it after the end of the transaction
                                        InitKeyType = InitKeyType.Attribute //Read primary key auto increment column information from entity properties
                                    });

                string sql = @"SELECT top 10000 Name FROM SYSOBJECTS WHERE TYPE='U' ORDER BY Name";  //Query all linked database names
                var strList = db.SqlQueryable<databaseName>(sql).ToList();
                result.info = Newtonsoft.Json.JsonConvert.SerializeObject(strList);
                result.res = true;
                result.msg = "Query succeeded!";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //Generating entities
        public JsonResult GenerateEntity(string Link, string Name,string TableName,string type)
        {

            ResultInfo result = new ResultInfo();
            try
            {
                //Configure database connection
                SqlSugarClient db = new SqlSugarClient(
                                    new ConnectionConfig()
                                    {
                                        ConnectionString = "" + Link + ";database=" + Name + "",
                                        DbType = DbType.SqlServer,//Set database type
                                        IsAutoCloseConnection = true,//Automatically release the data service. If there is a transaction, release it after the end of the transaction
                                        InitKeyType = InitKeyType.Attribute //Read primary key auto increment column information from entity properties
                                    });

                string path = "C:\\Demo\\2";

                if (type == "0")
                {
                    path = "C:\\Demo\\2";
                    db.DbFirst.Where(TableName).CreateClassFile(path);
                    result.info = System.IO.File.ReadAllText(@"" + path + "\\" + TableName + ".cs" + "", Encoding.UTF8);
                }
                else if (type == "1")
                {
                    path = "C:\\Demo\\3";
                    db.DbFirst.IsCreateAttribute().CreateClassFile(path);
                    result.info = "";
                }

                
                
                result.res = true;
                result.msg = "Generated successfully!";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //View when generating all tables
        public JsonResult GetGenerateEntity(string TableName)
        {

            ResultInfo result = new ResultInfo();
            try
            {
                string path = "C:\\Demo\\3";
                result.info = System.IO.File.ReadAllText(@"" + path + "\\" + TableName + ".cs" + "", Encoding.UTF8);
                result.res = true;
                result.msg = "Query succeeded!";
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                try
                {
                    if (result.msg.Contains("Could not find file"))
                    {
                       string path = "C:\\Demo\\2";
                        result.info = System.IO.File.ReadAllText(@"" + path + "\\" + TableName + ".cs" + "", Encoding.UTF8);
                        result.res = true;
                        result.msg = "Query succeeded!";
                    }
                }
                catch (Exception)
                {
                    result.msg = ex.Message;
                }
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        //Database name
        public class databaseName
        {
            public string Name { get; set; }
        }

        //Encapsulate return information data
        public class ResultInfo
        {
            public ResultInfo()
            {
                res = false;
                startcode = 449;
                info = "";
            }
            public bool res { get; set; }  //Return to status( true or false)
            public string msg { get; set; }  //Return information
            public int startcode { get; set; }  //return http Status code of
            public string info { get; set; }  //Results returned( res by true Returns the result set, res by false Error prompt)
        }

    }
}

 

 

 

Such a set of visual code generator will come out. We will publish it to IIS, and then set it to browser label (Collection), so that it can be used quickly.

Let's run it to see if it's convenient!

 

Welcome to subscribe to my wechat public platform [Xiong zeyouhua], more interesting and easy to learn knowledge, etc
Author: Xiong Ze - pain and joy in learning
Official account: Bear's saying
source:  https://www.cnblogs.com/xiongze520/p/13181241.html
It is not easy to create. The copyright belongs to the author and the blog park. Please indicate the link between the author and the original text in the obvious position of the article.  

 

Posted by bubbadawg on Mon, 22 Jun 2020 21:42:08 -0700