Skip to content

数据库连接选择属性

此特性为活字格V9.0.100.0新增功能

csharp
    public class MyPluginServerCommand : Command, ICommandExecutableInServerSideAsync
    {
        [DatabaseConnectionSelectorProperty]
        public string Connection { get; set; }

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var dataAccess = dataContext.DataAccess;
            var connectionStr = dataAccess.GetConnectionStringByID(Connection);

            dataAccess.BeginTransaction(connectionStr);
            try
            {
                var result = await dataAccess.ExecuteSqlAsync(Connection, "select * from 表1", null);
                dataAccess.CommitTransaction(connectionStr);
            }
            finally
            {
                dataAccess.RollbackTransaction(connectionStr);
            }
            return new ExecuteResult();
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }

在设计器中效果如下

在数据库连接管理中连接了一些外链数据库之后
1693546737960-3f9b7f6e-e2e4-41df-9e4e-f6eeaa11c15b.png

可以通过标注了DatabaseConnectionSelectorProperty的属性选择特定数据库
1693554235770-89e45489-eba5-4710-9c19-8caf5e5c2075.png

如果需要更细致的控制,可以通过DatabaseConnectionSelectorProperty的其他属性来控制

  1. (空)显示为内建库
    1. 设置DatabaseConnectionSelectorProperty的IncludeBuiltInDatabase属性
    2. 代码
csharp
    public class MyPluginServerCommand : Command, ICommandExecutableInServerSideAsync
    {
        [DatabaseConnectionSelectorProperty(IncludeBuiltInDatabase = true)]
        public string Connection { get; set; }

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var dataAccess = dataContext.DataAccess;
            var connectionStr = dataAccess.GetConnectionStringByID(Connection);

            dataAccess.BeginTransaction(connectionStr);
            try
            {
                var result = await dataAccess.ExecuteSqlAsync(Connection, "select * from 表1", null);
                dataAccess.CommitTransaction(connectionStr);
            }
            finally
            {
                dataAccess.RollbackTransaction(connectionStr);
            }
            return new ExecuteResult();
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
3. 效果  

1693554312019-d4ff571f-3810-48d6-893d-56cf3c210382.png 4. 说明 1. 对于内建数据库(Sqlite)连接名称为null

注意,标注DatabaseConnectionSelectorProperty的属性类型必须是 string

更新: 2023-11-02 09:49:21
原文: https://www.yuque.com/robert-bh51n/ea8l6c/gn2xgx68ggo0igsa