WebApi Swagger基础上使用Sqlsugar

第一步:
在startup.cs文件中 注册sqlsugar
在这里插入图片描述
第二步:
新建DBContext.cs文件,代码如下:

using SqlSugar;
using System;
using System.Linq;

namespace FirstApi
{
    public class DBContext
    {
        private string connectionString = null;
        private DbType dbType = DbType.SqlServer;
        public static string DB_ConnectionString { get; set; }
        public static DbType DB_dbType { get; set; }


        public DBContext() : this(DB_dbType, DB_ConnectionString)
        {

        }
        //public DBContext(string dbType) : this((DbType)Enum.Parse(typeof(DbType), dbType), DB_ConnectionString)
        //{

        //}

        public DBContext(string dbType, string connectionString) : this((DbType)Enum.Parse(typeof(DbType), dbType), DB_ConnectionString)
        {

        }

        public DBContext(DbType DB_dbType, string DB_ConnectionString)
        {
            //this.connectionString = connectionString;
            this.connectionString = DB_ConnectionString;
            this.dbType = DB_dbType;
            this.Database = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = this.connectionString,
                DbType = this.dbType,
                //DbType = dbType,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });
            //调式代码 用来打印SQL 
            this.Database.Aop.OnLogExecuting = (sql, pars) =>
            {
            Console.WriteLine(sql + "\r\n" +
                this.Database.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            Console.WriteLine();
            };
            this.Database.Ado.IsEnableLogEvent = true;
        }
        public SqlSugarClient Database { get; private set; }
    }
}

第三步:
在项目下新建一个文件夹,命名为T4
在这里插入图片描述
第四步:
在T4下新建一个“文本文件”,并将后缀改为.tt
在这里插入图片描述
打开此test.tt文件,将以下代码复制进去【数据库连接信息等需要修改】:

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="$(SolutionDir)\CYM.Lib\Newtonsoft.Json.dll" #>
<#@ assembly name="$(SolutionDir)\CYM.Lib\SqlSugar.dll" #>
<#@ assembly name="$(SolutionDir)\CYM.Lib\Oracle.ManagedDataAccess.dll" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ assembly name="System.Data" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="SqlSugar" #>
<#@ import namespace="Newtonsoft.Json" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Web" #>

<# 
    //CTRL+S将会执行该文件的代码,自动作生实体
    //当前项目目录
    string projectDir = Host.ResolveAssemblyReference("$(ProjectDir)");
    //解决方案目录
    string solutionDir = Host.ResolveAssemblyReference("$(SolutionDir)");
     var db = new SqlSugarClient(new ConnectionConfig() { 
                ConnectionString =  @"Data Source=localhost/ORCL;Persist Security Info=True;User ID=scott;Password=tiger",
                DbType = SqlSugar.DbType.Oracle, 
                IsAutoCloseConnection = true,
                  InitKeyType = InitKeyType.Attribute});
	List<DbTableInfo> list = db.DbMaintenance.GetTableInfoList();
                    List<DbTableInfo> viewList = db.DbMaintenance.GetViewInfoList();
                    //表
                    foreach (DbTableInfo table in list)
                    {
                        string table_name =StringUtil.ToCase(table.Name);
                        db.MappingTables.Add(table_name, table.Name);
                        List<DbColumnInfo> dd = db.DbMaintenance.GetColumnInfosByTableName(table.Name);
                        foreach (DbColumnInfo item in dd)
                        {
                            db.MappingColumns.Add(StringUtil.ToCase(item.DbColumnName), item.DbColumnName, table_name);              
                        }
                        db.DbFirst.IsCreateAttribute().Where(table.Name).CreateClassFile(projectDir+"\\Models\\TableModel","FirstApi.Models.TableModel");
                    }
                    //视图
                    for (int i =0;i< viewList.Count;i++)
                    {
                        DbTableInfo table=viewList[i];
                        string table_name =StringUtil .ToCase(table.Name);
                        db.MappingTables.Add(table_name, table.Name);
                        List<DbColumnInfo> dd = db.DbMaintenance.GetColumnInfosByTableName(table.Name);
                        foreach (DbColumnInfo item in dd)
                        { 
                            db.MappingColumns.Add(StringUtil .ToCase(item.DbColumnName), item.DbColumnName, table_name);     
                        }
                        db.DbFirst.IsCreateAttribute().Where(table.Name).CreateClassFile(projectDir+"\\Models\\ViewModel","FirstApi.Models.ViewModel");
                    }
#>

<#+
public class StringUtil{
	 /// <summary>
        /// 首字母转大写
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToCase(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return string.Empty;
            }
            string[] arry = value.Split('_');
            string str = "";
            foreach (string item in arry)
            {
                string newstr = item.Replace("(", "").Replace(".", "").Replace(")", "");
                string firstLetter = newstr.Substring(0, 1);
                string rest = newstr.Substring(1, newstr.Length - 1);
                str += firstLetter.ToUpper() + rest+"_";
            }
            return str.Substring(0,str.Length - 1);
        }
}
#>

注意:
这三个dll文件,需要复制粘贴进本项目文件夹中
在这里插入图片描述
在这里插入图片描述
第五步:
在此test.tt文件下ctrl+s,会自动生成TableModel和ViewModel,
分别对应指定数据库中的所有表和所有视图。
在这里插入图片描述
在这里插入图片描述
第六步:
在控制器文件夹下的cs文件里,进行sqlsugar等代码的编写,程序调试。
在这里插入图片描述
sqlsugar的基础语法和打印:
在这里插入图片描述

发布了10 篇原创文章 · 获赞 0 · 访问量 178

猜你喜欢

转载自blog.csdn.net/weixin_42046939/article/details/104021240
今日推荐