Blazor + SqlSugar 实现单表增删改功能

效果图

前台代码

复制代码
@page "/UserAccount/Index"

<Table TItem="BlazorORM.Entity.UserAccount"
       IsPagination="true" PageItemsSource="new int[] {10, 20}"
       IsStriped="true" IsBordered="true"
       ShowToolbar="true" ShowSearch="true" IsMultipleSelect="true" ShowExtendButtons="true"
       AddModalTitle="增加类型" EditModalTitle="修改类型"
       SearchModel="@SearchModel" ShowEmpty="true" SearchMode="SearchMode.Top" EditDialogSize="Size.Medium"
       OnQueryAsync="@OnSearchModelQueryAsync" OnResetSearchAsync="@OnResetSearchAsync"
       OnAddAsync="@OnAddAsync" OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.Account" Text="账号" />
        <TableColumn @bind-Field="@context.Name" Text="名称" />
        @*<TableColumn @bind-Field="@context.Password" Text="密码" />*@
        <TableColumn @bind-Field="@context.CreateTime" Width="180" Text="创建时间" Editable="false" />
    </TableColumns>
    <EditTemplate>
        <div class="row g-3 form-inline">
            <div class="col-12 col-sm-6">
                <BootstrapInput @bind-Value="@context.Account" PlaceHolder="请输入" ShowLabel="true" DisplayText="账号" />
            </div>
            <div class="col-12 col-sm-6">
                <BootstrapInput @bind-Value="@context.Name" PlaceHolder="请输入" ShowLabel="true" DisplayText="名称" />
            </div>
        </div>
        <div class="row g-3 form-inline" style="margin-top:2px;">
            <div class="col-12 col-sm-12">
                <BootstrapPassword @bind-Value="@context.Password" PlaceHolder="请输入" ShowLabel="true" DisplayText="密码" />
            </div>
        </div>
    </EditTemplate>
    <SearchTemplate>
        <div class="row g-3 form-inline">
            <div class="col-12 col-sm-6">
                <BootstrapInput @bind-Value="@context.Account" PlaceHolder="请输入" ShowLabel="true" DisplayText="账号" />
            </div>
            <div class="col-12 col-sm-6">
                <BootstrapInput @bind-Value="@context.Name" PlaceHolder="请输入" ShowLabel="true" DisplayText="名称" />
            </div>
        </div>
    </SearchTemplate>
</Table>

<style>
    .input-group {
        display: none;
    }

    .form-inline .form-label {
        width: 50px;
    }
</style>

后台代码

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.JSInterop;
using BlazorApp;
using BlazorApp.Shared;
using BootstrapBlazor.Components;
using BlazorService;
using System.Diagnostics.CodeAnalysis;

namespace BlazorApp.Pages.UserAccount
{
    public partial class Index
    {
        //弹窗组件
        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }


        //数据库业务处理对象
        UserAccountBll bll = new UserAccountBll();

        //查询条件对象
        private BlazorORM.Entity.UserAccount SearchModel { get; set; } = new BlazorORM.Entity.UserAccount();

        

        /// <summary>
        /// 清空搜索
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private static Task OnResetSearchAsync(BlazorORM.Entity.UserAccount item)
        {
            item.Name = "";
            item.Account = "";
            return Task.CompletedTask;
        }


        /// <summary>
        /// 查询事件
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        private Task<QueryData<BlazorORM.Entity.UserAccount>> OnSearchModelQueryAsync(QueryPageOptions options)
        {
            int total = 0;
            var items = bll.GetPageList(SearchModel.Account, SearchModel.Name, options.PageIndex - 1, options.PageItems, total);
            return Task.FromResult(new QueryData<BlazorORM.Entity.UserAccount>()
            {
                Items = items,
                TotalCount = total,
                IsSorted = true,
                IsFiltered = options.Filters.Any(),
                IsSearch = options.Searches.Any(),
                IsAdvanceSearch = options.AdvanceSearches.Any()
            });
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        private static Task<BlazorORM.Entity.UserAccount> OnAddAsync() => Task.FromResult(new BlazorORM.Entity.UserAccount() { CreateTime = DateTime.Now });

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="item"></param>
        /// <param name="changedType"></param>
        /// <returns></returns>
        private Task<bool> OnSaveAsync(BlazorORM.Entity.UserAccount item, ItemChangedType changedType)
        {
            try
            {
                bool result = false;
                // 增加数据演示代码
                if (changedType == ItemChangedType.Add)
                {
                    item.ID = Guid.NewGuid();

                    if (bll.GetByName(item.Name) != null)
                    {
                        
                        ToastService.Show(new ToastOption()
                        {
                            Category = ToastCategory.Error,
                            Title="消息提醒",
                            Content = "名称重复"
                        });
                        
                        return Task.FromResult(false);
                    }
                    if (bll.GetByAcccount(item.Account) != null)
                    {
                        
                        ToastService.Show(new ToastOption()
                        {
                            Category = ToastCategory.Error,
                            Title = "消息提醒",
                            Content = "账号重复"
                        });
                        
                        return Task.FromResult(false);
                    }
                    result = bll.Add(item);
                }
                else
                {
                    result = bll.Update(item);
                }
                
                return Task.FromResult(true);
            }
            catch (Exception ex)
            {
                
                ToastService.Show(new ToastOption()
                {
                    Category = ToastCategory.Error,
                    Title = "消息提醒",
                    Content = ex.Message
                });
                
                return Task.FromResult(false);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        private Task<bool> OnDeleteAsync(IEnumerable<BlazorORM.Entity.UserAccount> items)
        {
            var result = bll.DeleteByIds(items.ToList());
            
            return Task.FromResult(result);
        }
    }
}

业务处理代码

复制代码
using BlazorORM;
using BlazorORM.Entity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace BlazorService
{
    public class UserAccountBll : SqlSugarBase
    {
        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="account"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<UserAccount> GetPageList(string account, string name, int pageIndex, int pageSize, int totalCount)
        {
            return DB.Queryable<UserAccount>()
                .With(SqlWith.NoLock)
                .WhereIF(string.IsNullOrEmpty(account) == false, x => x.Account.Contains(account))
                .WhereIF(string.IsNullOrEmpty(name) == false, x => x.Name.Contains(name))
                .OrderBy(x => x.IDQue)
                .ToPageList(pageIndex, pageSize, ref totalCount);
        }
        /// <summary>
        /// 根据名称获取
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public UserAccount GetByName(string name)
        {
            return DB.Queryable<UserAccount>()
                .With(SqlWith.NoLock)
                .Where(x => x.Name == name).ToList().FirstOrDefault();
        }
        /// <summary>
        /// 根据账号获取
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public UserAccount GetByAcccount(string account)
        {
            return DB.Queryable<UserAccount>()
                .With(SqlWith.NoLock)
                .Where(x => x.Account == account).ToList().FirstOrDefault();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Add(UserAccount entity)
        {
            return DB.Insertable<UserAccount>(entity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update(UserAccount entity)
        {
            return DB.Updateable<UserAccount>(entity).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entitysList"></param>
        /// <returns></returns>
        public bool DeleteByIds(List<UserAccount> entitysList)
        {
            return DB.Deleteable<UserAccount>(entitysList).ExecuteCommand() > 0;
        }

    }
}
相关推荐
ji_shuke2 分钟前
远程排查 Web 系统问题:如何导出 HAR 文件协助定位
前端·问题排查
程序员爱钓鱼29 分钟前
Rust String 与 &str 详解:字符串所有权、借用与转换
前端·后端·rust
码农学院34 分钟前
GEO与SEO协同:从传统搜索到生成式搜索的平滑迁移路径
服务器·前端·python
To_OC8 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮9 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny9 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹9 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
阳光是sunny9 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
To_OC10 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn10 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js