.net core3.1 MVC使用sqlsugar方式操作mysql數據庫


一、創建項目

本來這個項目是寫SQLite數據庫的,但連接字符串,老不成功,郁悶死了,改成使用這個MySQL5.7數據庫了。但大體一樣的,大家能完全感覺到SqlSugar的強大。

因我是小白菜,可能寫法不科學,請大家見諒,希望有幫助。

在此,先給SqlSugar打個廣告:國人的產品,體量是EF30分之一,速度快,操作簡單,就是說明書太少,希望大家頂一下。

 

 

 

這個步略了吧。我選擇的是WEB模型視圖控制器

二、安裝支持Mysql.Data 包 

 

 

 

 

 

三、ORM的使用,安裝SqlSugar包

安裝 ORM用的是SqlSugar

 

 

 

 三、用數據庫管理軟件先弄一個現成的Mysql數據庫

1.先安裝MySql5.7。聽說5.8以后要收費的哩。安裝教程網上很多,就不多說了,我用Navicat進入管理 

新建數據庫Test,建表Users

 

 

 

 

 上圖很清楚了,不細說拉,先添加幾個默認的數據進去。

 六、配置數據庫連接服務

1.把數據庫的連接語句寫到appsettings.json里面:

{
  "DBConnection": {
     "MySqlConnectionString": "server=localhost;database=test;uid=root;pwd=xxyyzz&;charset='utf8';SslMode=None"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

  

2.創建一個讀取訪問該字符串的類ConfigExtensions.cs,當然網上很多現成的,我也隨便拉了一個。

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace gosqlite.DAL
{
    public class ConfigExtensions
    {
        public static IConfiguration Configuration { get; set; }
        static ConfigExtensions()
        {
            //ReloadOnChange = true 當appsettings.json被修改時重新加載            
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            .Build();
        }
        /// <summary>
        /// 獲得配置文件的對象值
        /// </summary>
        /// <param name="jsonPath"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetJson(string jsonPath, string key)
        {
            IConfiguration config = new ConfigurationBuilder().AddJsonFile(jsonPath).Build(); //json文件地址
            string s = config.GetSection(key).Value; //json某個對象
            return s;
        }
        /// <summary>
        /// 根據配置文件和Key獲得對象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">文件名稱</param>
        /// <param name="key">節點Key</param>
        /// <returns></returns>
        public static T GetAppSettings<T>(string fileName, string key) where T : class, new()
        {
            var baseDir = AppContext.BaseDirectory + "json/";
            var currentClassDir = baseDir;

            IConfiguration config = new ConfigurationBuilder()
                .SetBasePath(currentClassDir)
                .Add(new JsonConfigurationSource { Path = fileName, Optional = false, ReloadOnChange = true })
                .Build();
            var appconfig = new ServiceCollection().AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }
    }
}

 

3.建一個SqlSugar連接數據庫的類MyContext.cs

using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
namespace gosqlite.DAL
{
    public class MyContext
    {    
        public static IConfiguration Configuration { get; set; }
        public MyContext()
        {
              Db11 = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConfigExtensions.Configuration["DbConnection:MySqlConnectionString"],
                DbType = DbType.MySql,
                IsAutoCloseConnection = true
            });
            //Print sql
            Db11.Aop.OnLogExecuting = (sql, pars) =>
            {
                Console.WriteLine(sql + "\r\n" + Db11.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Console.WriteLine();
            };          
        }
        public SqlSugarClient Db11;//用來處理事務多表查詢和復雜的操作
    }
}

然后,配置就基本好了,下一步主是在MVC中用SqlSugar實現CRUN功能。

四.控制台中使用

1.增加表的實體模型

在Model下新建模型Users.cs,這個和數據庫相皮配

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace testsqlite2.Models
{
    public class Users
    {
        public int ID { get; set; }       //主鍵
        public string Name { get; set; }  //用戶名稱
        public int Age { get; set; }    //用戶年齡
        public int Number { get; set; } //用戶手機號碼
    }
}

 打開自帶的HomeController控制器

 我寫了三個方法 ,一個INDEX視圖是讀取User表進行顯示,一個是增加記錄ADD(),一個是刪 除記錄DelItem().沒有加判斷,因為僅是測試使用。

   public IActionResult Index()
        {
              MyContext db = new MyContext();
              var list = db.Db11.Queryable<Users>().ToList();//Search
              return View(list);        }

        public IActionResult ADD()
        {
            MyContext db = new MyContext();
            Users newadd =new Users();
            int time1 = Convert.ToInt32(DateTime.Now.ToString("yyHHmmss"));
            newadd.Name = "test"+ DateTime.Now.ToString("yyHHmmss");
            newadd.ID = time1;
            newadd.Age = 5;
            newadd.Number = 55;
            db.Db11.Insertable(newadd).ExecuteCommand();
            return RedirectToAction("Index");
        }

        public IActionResult Delitem(int? ID)
        {
            MyContext db = new MyContext();
            db.Db11.Deleteable<Users>(ID).ExecuteCommand();
            return RedirectToAction("Index");
        }

  首先使用 MyContext db = new MyContext();實例SqlSugar,然后直接按他的入門教程中的一條操作記錄主可以拉。

因為index()方法 中,返回的是Users記錄合集,所以我在視圖上引用了@model List<Users>

下面是index視圖源碼

@model List<Users>
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <a href="./Home/ADD">新增一條記錄</a>
</div>1111111111111
<div class="panel panel-default todo-panel">
    <div class="panel-heading">@ViewData["Title"]</div>

    <table class="table table-hover">
        <thead>
            <tr>
                <td>✔</td>
                <td>ID</td>
                <td>Name</td>
                <td>Age</td>
                <td>Number</td>
                <td></td>
            </tr>
        </thead>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    <input type="checkbox" class="done-checkbox">
                </td>
                <td>@item.ID</td>
                <td>@item.Name</td>
                <td>@item.Age</td>
                <td>
                    @item.Number
                </td>
                <td>   <a href="./Home/Delitem/@item.ID">刪除</a> </td>
            </tr>
        }
    </table>

    <div class="panel-footer add-item-form">
        <!-- TODO: Add item form -->
    </div>
</div>
1111111111111

 實際效果如下

 

 

 

 這是我摸索了二天,感覺可行吧,但不知道具體流程對不,希望對大家有幫助。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM