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

发布时间:2023年12月29日

效果图

?前台代码

@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;
        }

    }
}

文章来源:https://blog.csdn.net/qq873113580/article/details/135290587
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。