基于Blazor Server+EF Core+Bootstratp Blazor 进行的基本增删改查

本次使用Vs2022+.net 6

一、创建项目使用Blazor Server

 二、引用以下的安装包

BootstrapBlazor
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Toolss

三、创建一个Model类

 

    [Table("SKModel")]
    public class SKModel
    {
        [Key]
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public string Address { get; set; }
    }

 

  

 

四、创建一个DBContext 

public class DbContext:DbContext
    {
        public DbContext(DbContextOptions options) : base(options)
        {
        }
        public DbSet<SKModel> SKModels { get; set; }
    }

五、在Program.cs中进行注入

//把BootstrapBlazor注入了
builder.Services.AddBootstrapBlazor();
//上下文注入
builder.Services.AddDbContextFactory<DbContext>(opt =>
      //链接数据库
      opt.UseSqlServer($"Data Source=.;Initial Catalog=SKBlazor;User ID=sa;Password=123456"));

六、进行迁移

 先在控制台执行 进行创建数据库

 Add-Migration SQL1

成功后在执行

 update-database newSQL

七、在_Imports.razor引用

@using BootstrapBlazor.Components

八、在Pages中_Layout.cshtml里进行替换 

 <!-- 需引用 BootstrapBlazor.FontAwesome 包 !-->
    <link href="_content/BootstrapBlazor.FontAwesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="_content/BootstrapBlazor/css/bootstrap.blazor.bundle.min.css" rel="stylesheet">

 @*新添加的*@
    <script src="_content/BootstrapBlazor/js/bootstrap.blazor.bundle.min.js"></script>

 九、在Pages文件夹下增加User.razor文件

 

@page "/user"
@using BlazorSKP.Model
@using Microsoft.EntityFrameworkCore;
@using BlazorSKP.Dal
@implements IDisposable
@inject IDbContextFactory<DbContext> DbFactory
 
     
<Table TItem="SKModel"
       IsPagination="true"
       IsStriped="true" IsBordered="true" IsMultipleSelect="true"
       ShowToolbar="true" ShowExtendButtons="true" ShowSkeleton="true"
       OnQueryAsync="@OnEditQueryAsync" OnResetSearchAsync="@OnResetSearchAsync"
       OnAddAsync="@OnAddAsync" OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync">
    <TableColumns>
        <TableColumn @bind-Field="@context.Id" Width="180" />
        <TableColumn @bind-Field="@context.Name" Sortable="true" Filterable="true" Text="名称" />
        <TableColumn @bind-Field="@context.Age" Text="年龄" />
        <TableColumn @bind-Field="@context.Address" Text="地址" />
    </TableColumns>
    <EditTemplate>
        <div class="form-inline">
            <div class="row">
                <div class="form-group col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.Name" placeholder="不可为空,50字以内" maxlength="50">
                        <RequiredValidator />
                        <StringLengthValidator Length="50" />
                    </BootstrapInput>
                </div>
                <div class="form-group col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.Age" placeholder="不可为空,50字以内" maxlength="50">
                        <RequiredValidator />
                        <StringLengthValidator Length="50" />
                    </BootstrapInput>
                </div>
                <div class="form-group col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.Address" placeholder="不可为空,50字以内" maxlength="50">
                        <RequiredValidator />
                        <StringLengthValidator Length="50" />
                    </BootstrapInput>
                </div>
            </div>
        </div>
    </EditTemplate>
</Table>
 
@code {
    private DbContext Context { get; set; }
    //这里相当于是构造方法
    protected override async Task OnInitializedAsync()
    {
        Context = DbFactory.CreateDbContext();
        await base.OnInitializedAsync();
    }
    protected async Task<SKModel> OnAddAsync()
    {
        return await Task.FromResult(new SKModel());
    }
    protected async Task<bool> OnSaveAsync(SKModel item, ItemChangedType type)
    {
        if(type==ItemChangedType.Add)
        {
            //数据保存
            await Context.AddAsync(item);
            await Context.SaveChangesAsync();
            return await Task.FromResult(true);
        }
        else{
            //数据更新
            var f = Context.SKModels.OfType<SKModel>().FirstOrDefault(i => i.Id == item.Id);
            if(f!=null)
            {
                f.Name = item.Name;
                f.Age = item.Age;
                f.PhoneNum = item.PhoneNum;
            }
            await Context.SaveChangesAsync();
        }
        return await Task.FromResult(true);
    }
    //删除
    protected async Task<bool> OnDeleteAsync(IEnumerable<SKModel> items)
    {
        items.ToList().ForEach(i => Context.SKModels.Remove(i));
        await Context.SaveChangesAsync();
        return await Task.FromResult(true);
    }
    //数据显示
    protected async Task<QueryData<SKModel>> OnEditQueryAsync(QueryPageOptions options)
    {
        var query = Context.SKModels;
        var ret = new QueryData<SKModel>()
            {
                
                TotalCount = query.Count(),
                Items = query
            };
 
        return await Task.FromResult(ret);
    }
    protected Task OnResetSearchAsync(SKModel item)
    {
        item.Name = "";
        item.Address = "";
        return Task.CompletedTask;
    }
 
    //释放上下文
    public void Dispose()
    {
        Context.Dispose();
    }
}

 

十、在NavMenu.razor里配置路由

十一、运行起来就完成了增删改查的基本操作

 

最开始学的时候借鉴了这位大佬的:https://www.cnblogs.com/kismet82/p/14321674.html

这是演示平台地址:https://www.blazor.zone/introduction

有问题的话请留言

 

      待续......

 

posted @ 2022-09-15 14:53  魔术人生  阅读(1632)  评论(0)    收藏  举报
复制代码