ASP.NET Core MVC+Layui使用EF Core連線MySQL執行簡單的CRUD操作

追逐時光者發表於2020-06-01

前言:

  本章主要通過一個完整的示例講解ASP.NET Core MVC+EF Core對MySQL資料庫進行簡單的CRUD操作,希望能夠為剛入門.NET Core的小夥伴們提供一個完整的參考例項。關於ASP.NET Core MVC+EF操作MsSQL Server詳情請參考官方文件(https://docs.microsoft.com/zh-cn/aspnet/core/data/ef-mvc/?view=aspnetcore-3.1)。

示例實現功能預覽:

 部落格例項原始碼下載地址:

https://github.com/YSGStudyHards/ASP.NET-Core-MVC-Layui-EF-Core-CRUD_Sample

一、建立ASP.NET Core Web應用程式:

注意,本章節主要以APS.NET Core 3.1版本作為部落格的樣式例項!

 

二、新增EF Core NuGet包:

  若要在專案中使用EF Core操作MySQL資料庫,需要安裝相應的資料庫驅動包。 本章教程主要使用 MySQL資料庫,所以我們需要安裝相關驅動包MySql.Data.EntityFrameworkCore。

安裝方式:

點選工具=>NuGet包管理器=>程式包管理器控制檯輸入以下命令:

Install-Package MySql.Data.EntityFrameworkCore -Version 8.0.20

點選工具=>NuGet包管理器=>管理解決方案的NuGet程式包:

搜尋:MySql.Data.EntityFrameworkCore  點選安裝。

三、建立對應資料庫表的實體模型:

   注意該篇部落格使用的是手動模型優先的方式進行資料庫表欄位與模型屬性對映,當然如果大家覺得這樣子比較麻煩的話可以真正意義上的模型優先,直接建立模型在program.cs中配置建立對應模型的資料庫邏輯程式碼即可無需手動建立資料庫,可參考官網文件教程(https://docs.microsoft.com/zh-cn/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&tabs=visual-studio#create-the-database)。

建立使用者模型(UserInfo):

注意:屬性大小寫和資料庫中的表欄位保持一致,Id 屬性成為此類對應的資料庫表的主鍵列。 預設情況下,EF Core 將名為 Id 或 xxxID 的屬性視為主鍵。 有關詳細資訊,請參閱 F Core - 金鑰

    /// <summary>
    /// 學生資訊模型
    /// </summary>
    public class UserInfo
    {
        /// <summary>
        /// 學生編號
        /// </summary>
        [Description("學生編號")]
        public int? Id { get; set; }

        /// <summary>
        /// 學生姓名
        /// </summary>
        [Description("學生姓名")]
        public string UserName { get; set; }

        /// <summary>
        /// 學生性別
        /// </summary>
        [Description("學生性別")]
        public string Sex { get; set; }

        /// <summary>
        /// 學生聯絡電話
        /// </summary>
        [Description("學生聯絡電話")]
        public string Phone { get; set; }

        /// <summary>
        /// 學生描述
        /// </summary>
        [Description("學生描述")]
        public string Description { get; set; }

        /// <summary>
        /// 學生愛好
        /// </summary>
        [Description("學生愛好")]
        public string Hobby { get; set; }
    }

四、將資料庫連線字串新增到 appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
        "MySqlConnection":"Data Source=127.0.0.1;User ID=root;Password=root;DataBase=SchoolUserInfo_db"
  }
}

五、建立資料庫上下文:

概述:

 資料庫上下文類是為給定資料模型協調 EF Core 功能的主類。 上下文派生自 Microsoft.EntityFrameworkCore.DbContext。 上下文指定資料模型中包含哪些實體。 在此專案中將資料庫上下文類命名為 SchoolUserInfoContext。

建立:

using Microsoft.EntityFrameworkCore;
using Model;

namespace Dal
{
    public class SchoolUserInfoContext : DbContext
    {
        public SchoolUserInfoContext(DbContextOptions<SchoolUserInfoContext> options)
            : base(options)
        {
        }

        /// <summary>
        /// DbSet實體集屬性對應資料庫中的表(注意實體集名必須與表明一致)
        /// </summary>
        public DbSet<UserInfo> UserInfos { get; set; }

        /// <summary>
        /// TODO:當資料庫建立完成後, EF 建立一系列資料表,表名預設和 DbSet 屬性名相同。 集合屬性的名稱一般使用複數形式,但不同的開發人員的命名習慣可能不一樣,
/// 開發人員根據自己的情況確定是否使用複數形式。 在定義 DbSet 屬性的程式碼之後,新增下面程式碼,對DbContext指定單數的表名來覆蓋預設的表名。
/// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<UserInfo>().ToTable("UserInfo"); } } }

六、將上下文新增到 Startup.cs 中的依賴項注入:

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //注入EF Core資料庫上下文服務
            services.AddDbContext<SchoolUserInfoContext>(options =>
                options.UseMySQL(Configuration.GetConnectionString("MySqlConnection")));

            services.AddControllersWithViews();
        }

七:引入Layui樣式和js:

前往官網下載Layui相關樣式和js包,下載地址:https://www.layui.com/

Layui彈出層外掛layer.js(有很多地方需要用到彈窗),下載地址:https://layer.layui.com/

將相關檔案存放到wwwroot檔案下:

 

將相關檔案引入預設佈局頁面中:

八、 ASP.NET Core MVC 和 EF Core實現MySQL  CRUD功能:

注意在這裡主要展示的EF Core與資料庫操作的部分程式碼,詳細程式碼可下載例項原始碼檢視。

Create:

        /// <summary>
        /// 學生資訊新增
        /// </summary>
        /// <param name="addUserInfo"></param>
        /// <returns></returns>
        public async Task<bool> Create(AddUserInfoViewModel addUserInfo)
        {
            try
            {
                var userInfo=new UserInfo()
                {
                    UserName = addUserInfo.UserName,
                    Sex = addUserInfo.Sex,
                    Hobby = addUserInfo.Hobby,
                    Phone = addUserInfo.Phone,
                    Description = addUserInfo.Description
                };

                _shoSchoolUserInfoContext.UserInfos.Add(userInfo);

                await _shoSchoolUserInfoContext.SaveChangesAsync();

                return true;
            }
            catch
            {
                return false;
            }
        }

Retrieve:

        /// <summary>
        /// 獲取使用者資訊
        /// </summary>
        /// <param name="page">當前頁碼</param>
        /// <param name="limit">顯示條數</param>
        /// <param name="userName">使用者姓名</param>
        /// <returns></returns>
        public async Task<PageSearchModel> GetPageListData(int page = 1, int limit = 15, string userName = "")
        {
            try
            {
                List<UserInfo> listData;
                var totalCount = 0;
                if (!string.IsNullOrWhiteSpace(userName))
                {
                    listData = await _shoSchoolUserInfoContext.UserInfos.Where(x => x.UserName.Contains(userName)).OrderByDescending(x => x.Id).Skip((page - 1) * limit).Take(limit).ToListAsync();

                    totalCount = _shoSchoolUserInfoContext.UserInfos
                        .Count(x => x.UserName.Contains(userName));
                }
                else
                {
                    listData = await _shoSchoolUserInfoContext.UserInfos.OrderByDescending(x => x.Id).Skip((page - 1) * limit).Take(limit).ToListAsync();

                    totalCount = _shoSchoolUserInfoContext.UserInfos.Count();
                }

                return new PageSearchModel()
                {
                    ResultMsg = "success",
                    Code = 200,
                    TotalCount = totalCount,
                    DataList = listData
                };
            }
            catch (Exception e)
            {
                return new PageSearchModel() { Code = 400, ResultMsg = e.Message };
            }
        }

Update:

        /// <summary>
        /// 學生資訊修改
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<bool> Update(UserInfo userInfo)
        {

            try
            {
                _shoSchoolUserInfoContext.UserInfos.Update(userInfo);

                await _shoSchoolUserInfoContext.SaveChangesAsync();

                return true;
            }
            catch
            {
                return false;
            }
        }

Delete:

        /// <summary>
        /// 學生資訊刪除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> Delete(int? id)
        {
            try
            {
                var searchUserInfo = await _shoSchoolUserInfoContext.UserInfos.FindAsync(id);

                if (searchUserInfo == null)
                {
                    return false;
                }

                _shoSchoolUserInfoContext.UserInfos.Remove(searchUserInfo);
                await _shoSchoolUserInfoContext.SaveChangesAsync();

                return true;
            }
            catch
            {
                return false;
            }
        }

相關文章