Skip to content

关于 FreeSql.Cloud 多库操作服务

Alex chow edited this page Feb 9, 2024 · 11 revisions

基于 FreeSql.Cloud

注入 FreeSql.Cloud服务

    builder.Services.AddFreeSqlCloud(option =>
    {
        option.UseConnectionString(FreeSql.DataType.SqlServer, builder.Configuration["ConnectionString"])
#if DEBUG
             .UseNoneCommandParameter(true)
             //调试sql语句输出
             .UseMonitorCommand(cmd => System.Console.WriteLine(cmd.CommandText + Environment.NewLine))
#endif
        ;
    }, configureOptions: new FreeSqlServiceOptions(true));

    //全功能版
    builder.Services.AddTransient(typeof(FreeSqlDataService<>));

源码

表格组件使用参数ConnectionString 动态切换数据库

表格页面组件基类

基于身份验证扩展声明 DSID 生成连接字符串动态切换当前用户数据库

using BootstrapBlazor.Components;
using Densen.DataAcces.FreeSql;
using Densen.Service;
using FreeSql;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using System.Diagnostics.CodeAnalysis;
using System.Security.Claims;
using static Microsoft.Extensions.DependencyInjection.FreeSqlServiceCollectionExtensions;

public class AdminBase : ComponentBase
{

    [Inject]
    [NotNull]
    public FsqlCloud? fsqlCloud { get; set; }

    [Inject]
    [NotNull]
    public IFreeSql? fsql { get; set; }

    [Inject]
    [NotNull]
    public IConfiguration? Config { get; set; }

    [Inject]
    public FreeSqlServiceOptions? configureOptions { get; set; }

    /// <summary>
    /// 指定数据库连接字符串
    /// </summary>
    public string? ConnectionString { get; set; }

    /// <summary>
    /// 级联参数获取身份验证状态数据
    /// </summary>
    [CascadingParameter]
    [NotNull]
    public Task<AuthenticationState>? AuthenticationStateTask { get; set; }

    [NotNull]
    [Inject]
    public NavigationManager? NavigationManager { get; set; }

    public ClaimsPrincipal? User { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (!firstRender)
        {
            return;
        }

        User = (await AuthenticationStateTask).User;

        if (User != null)
        {
            var connectionString = User!.Claims.FirstOrDefault(c => c.Type == "DSID")?.Value;
            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                ConnectionString = await GenConnectionString(connectionString);
                if (fsqlCloud != null && ConnectionString != null)
                {
                    fsqlCloud.Register(ConnectionString, () =>
                    {
                        var builder = new FreeSqlBuilder()
                            .UseConnectionString(DataType.SqlServer, ConnectionString)
#if DEBUG
                            .UseNoneCommandParameter(true)
                            //调试sql语句输出
                            .UseMonitorCommand(cmd => System.Console.WriteLine(cmd.CommandText + Environment.NewLine))
#endif
                            ;

                        var instance = builder.Build();
                        instance.UseJsonMap();
                        if (configureOptions?.ConfigEntityPropertyImage ?? false)
                        {
                            instance.Aop.AuditValue += AuditValue;
                            instance.Aop.ConfigEntityProperty += ConfigEntityProperty;
                        }
                        return instance;

                    });

                    fsql = fsqlCloud.Use(ConnectionString);
                    StateHasChanged();
                }

            }
        }
    }

    private async Task<string?> GenConnectionString(string connectionString)
    {
        //自定义生成连接字符串过程
        connectionString = Config["ConnectionString"]?.Replace("demo", connectionString);
        return connectionString;
    }

}


表格组件例子

@page  "/productlist"
@inherits AdminBase
@attribute [TabItemOption(Text = "商品")]
@attribute [Authorize]

<PageTitle>商品</PageTitle>

<TableAmePro TItem="Products"
             ItemDetails="NullClass"
             ItemDetailsII="NullClass"
             ItemDetailsIII="NullClass"
             IsReadonly ='!User.IsInRoleAny("Administrators,Office超级用户,Superuser")'
             AllowDragColumn
             AllowResizing
             PageItems="20"
             ShowColumnList
             ConnectionString="@ConnectionString">
</TableAmePro> 

身份验证扩展

using System.Security.Claims;

public static partial class RoleExtensions
{
    public static bool IsInRoleAny(this ClaimsPrincipal? user, string role)
    {
        if (user == null)
        {
            return false;
        }
        var roles = role.Split(',');
        foreach (var r in roles)
        {
            if (user.IsInRole(r))
            {
                return true;
            }
        }

        return false;
    }
}