使用MYSQL时二级缓存的BUG 返回

SqlSugar 沟通中
5 359

5dcf2282-3e29-4028-965b-60960c59c9f7.png


配置的多库,使用的mysql数据库。

无实体查询时,传入表名“t_core_currency_other”,生成的sql不对,如图。

应该是 'samom_core'.'t_Core_Currency_Other',而框架全放在同一个引号里面了。

热忱回答5

  • fate sta fate sta VIP0
    2025/8/11

    传入t_core_currency_other 正常情况表名也是t_core_currency_other

    至于你说的是这个

     'samom_core'.'t_Core_Currency_Other

    需要提供完整DEMO和关键代码

    0 回复
  • 初始化缓存扩展方法:

    /// <summary>

        /// 初始化缓存

        /// </summary>

        public static void InitCache(this IApplicationBuilder app)

        {

            var uow = app.ApplicationServices.GetRequiredService<IUnitOfWork>();

            var cache = app.ApplicationServices.GetRequiredService<IMemoryCacheService>();


            using var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope();

            var modelMetaService = scope.ServiceProvider.GetRequiredService<IModelMetaService>();


            var models = uow.Db.Queryable<Model>().WithCache().ToList();

            var entities = uow.Db.Queryable<ModelEntity>().WithCache().ToList();

            var fields = uow.Db.Queryable<ModelField>().WithCache().ToList();

            uow.Db.Queryable<Form>().WithCache().ToList();

            uow.Db.Queryable<FormBlock>().WithCache().ToList();

            uow.Db.Queryable<FormField>().WithCache().ToList();

            uow.Db.Queryable<FormOperation>().WithCache().ToList();

            uow.Db.Queryable<FormBlockOperation>().WithCache().ToList();

            uow.Db.Queryable<FormQuickSearch>().WithCache().ToList();

            uow.Db.Queryable<FormColumn>().WithCache().ToList();

            uow.Db.Queryable<EnumType>().WithCache().ToList();

            uow.Db.Queryable<Domain.Entities.Core.Enum>().WithCache().ToList();

            uow.Db.Queryable<User>().WithCache().ToList();


            /*

                缓存基础资料

                无实体缓存需手动清理

                ctx.Db.DataCache.RemoveDataCache(entityId)

            */

            var ids = models.Where(x => x.Type == ModelType.Basic).Select(x => x.Id).ToList();

            var ens = entities.Where(x => ids.Contains(x.ModelId));

            foreach (var e in ens)

            {

                var list = uow.Db.Queryable<object>().AS(e.TableName).ToList();

                uow.Db.Queryable<object>().AS(e.TableName).WithCache(e.Id).ToList();

            }

        }


    uow接口:

    using SqlSugar;


    namespace SA.Domain.IRepository;


    public interface IUnitOfWork

    {

        public SugarUnitOfWork CreateContext();


        public ISqlSugarClient Db { get; }

    }


    uow实现:

    using SA.Domain.IRepository;

    using SqlSugar;


    namespace SA.Infrastructure.Repositories;


    public class UnitOfWork(ISqlSugarClient db) : IUnitOfWork

    {

        public SugarUnitOfWork CreateContext()

        {

            return db.CreateContext(db.Ado.IsNoTran());

        }


        public ISqlSugarClient Db { get { return db; } }

    }


    sqlsugar配置:

    using System.Reflection;

    using Microsoft.Extensions.DependencyInjection;

    using SA.Domain.Exceptions;

    using SA.Domain.IRepository;

    using SA.Domain.IServiceInfrastructure;

    using SA.Infrastructure.Repositories;

    using SqlSugar;


    namespace SA.Infrastructure.Setup;


    public static class SqlSugarSetup

    {

        public static void AddSqlsugarSetup(this IServiceCollection services)

        {

            var appSettingService = services.BuildServiceProvider().GetService<IApplicationSettingService>()

                ?? throw new ServiceNotFoundException(typeof(IApplicationSettingService));


            var cacheService = services.BuildServiceProvider().GetService<ICacheService>()

            ?? throw new ServiceNotFoundException(typeof(ICacheService));


            //主库连接配置

            var coreCC = new ConnectionConfig

            {

                ConfigId = "core",

                DbType = appSettingService.CoreDbType,

                ConnectionString = appSettingService.CoreConnection,

                IsAutoCloseConnection = true,

                ConfigureExternalServices = new ConfigureExternalServices()

                {

                    EntityService = (p, e) =>

                    {

                        e.DbColumnName = e.DbColumnName.ToUpper();


                        if (p.PropertyType == typeof(decimal) || p.PropertyType == typeof(decimal?))

                        {

                            e.Length = 23;

                            e.DecimalDigits = 10;

                        }


                        if (e.IsPrimarykey == false && new NullabilityInfoContext().Create(p).WriteState is NullabilityState.Nullable)

                        {

                            e.IsNullable = true;

                        }

                    },

                    EntityNameService = (p, e) =>

                    {

                        e.DbTableName = e.DbTableName.ToUpper();

                    },

                    DataInfoCacheService = cacheService,

                    SqlFuncServices =

                    [

                        new SqlFuncExternal

                        {

                            UniqueMethodName = "SaCoalesce",

                            MethodValue = (expInfo, dbType, expContext) =>

                            {

                                var memberNames = expInfo.Args.Select(x => x.MemberName);

                                return $"COALESCE({string.Join(",", memberNames)})";

                            }

                        }

                    ]

                },

                MoreSettings = new ConnMoreSettings()

                {

                    IsWithNoLockQuery = true,

                    SqlServerCodeFirstNvarchar = true,

                    IsAutoRemoveDataCache = true,//实体更新时自动清理缓存,该设置对于无实更新无效。

                    DefaultCacheDurationInSeconds = appSettingService.SqlSugarCacheExpiredSeconds

                }

            };


            //日志库连接配置

            var logCC = new ConnectionConfig

            {

                ConfigId = "log",

                DbType = appSettingService.LogDbType,

                ConnectionString = appSettingService.LogConnection,

                IsAutoCloseConnection = true,

                ConfigureExternalServices = new ConfigureExternalServices()

                {

                    EntityService = (x, p) =>

                    {

                        p.DbColumnName = p.DbColumnName.ToUpper();

                    },

                    EntityNameService = (x, p) =>

                    {

                        p.DbTableName = p.DbTableName.ToUpper();

                    }

                },

                MoreSettings = new ConnMoreSettings()

                {

                    IsWithNoLockQuery = true,

                    SqlServerCodeFirstNvarchar = true,

                },

            };


            void configAction(SqlSugarClient db)

            {

                //设置主库

                var core = db.GetConnectionScope("core");

                core.Aop.OnLogExecuting = (sql, parameters) =>

                {

                    //SQL转大写执行

                    sql = sql.ToUpper();

                    foreach (var p in parameters)

                    {

                        p.ParameterName = p.ParameterName.ToUpper();

                    }


                    if (appSettingService.Environment == "dev")

                    {

                        // 打印SQL语句

                        Console.WriteLine(DateTime.Now);

                        Console.WriteLine(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, parameters));

                        Console.WriteLine();

                    }

                };

                core.Ado.CommandTimeOut = appSettingService.CoreCommandTimeOut;


                //设置日志库

                var log = db.GetConnectionScope("log");

                log.Aop.OnLogExecuting = (sql, parameters) =>

                {

                    //SQL转大写执行

                    sql = sql.ToUpper();

                    foreach (var p in parameters)

                    {

                        p.ParameterName = p.ParameterName.ToUpper();

                    }


                    if (appSettingService.Environment == "dev")

                    {

                        // 打印SQL语句

                        Console.WriteLine(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, parameters));

                    }

                };

                log.Ado.CommandTimeOut = appSettingService.LogCommandTimeOut;

            }


            SqlSugarScope sqlSugar = new([coreCC, logCC], configAction);

            sqlSugar.GetConnectionScope("core").DbMaintenance.CreateDatabase();

            sqlSugar.GetConnectionScope("log").DbMaintenance.CreateDatabase();


            //获得所有实体类型

            Type[] entityTypes = [.. Assembly

                .Load("SA.Domain")

                .GetTypes()

                .Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttribute<SugarTable>() != null)];


            //获得主库实体类型

            Type[] coreEntityTypes = [.. entityTypes.Where(t => t.CustomAttributes.Any(atr => atr.AttributeType == typeof(TenantAttribute) && atr.ConstructorArguments.Any(arg => arg.Value != null && arg.Value.Equals("core"))))];

            sqlSugar.GetConnectionScope("core").CodeFirst.SetStringDefaultLength(200).InitTables(coreEntityTypes);


            //获得日志库实体类型

            Type[] logEntityTypes = [.. entityTypes.Where(t => t.CustomAttributes.Any(atr => atr.AttributeType == typeof(TenantAttribute) && atr.ConstructorArguments.Any(arg => arg.Value != null && arg.Value.Equals("log"))))];

            sqlSugar.GetConnectionScope("log").CodeFirst.SetStringDefaultLength(200).InitTables(logEntityTypes);


            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));        

            services.AddScoped<IModelEntityRepository,ModelEntityRepository>();

            services.AddScoped<IUserMessageRepository, UserMessageRepository>();

            services.AddScoped<ISystemNoticeRepository, SystemNoticeRepository>();


            services.AddSingleton<ISqlSugarClient>(sqlSugar);

            services.AddSingleton<IUnitOfWork, UnitOfWork>();

        }

    }



    0 回复
  • @fate sta:关键代码已贴出来

    0 回复
  • fate sta fate sta VIP0
    2025/8/11

    全文搜索一下samom_core 哪来的,ORM不会凭空多出这个前缀

    或者提供一个可以重现的DEMO

    0 回复
  • @fate sta:samom_core是数据库名,我配置了多库。

    0 回复