[]
        
(Showing Draft Content)

数据库连接选择属性

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

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

在设计器中效果如下:

在数据库连接管理中连接了一些外链数据库之后:

image

可以通过标注了DatabaseConnectionSelectorProperty的属性选择特定数据库。

image

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

(空)显示为内建库

  1. 设置DatabaseConnectionSelectorProperty的IncludeBuiltInDatabase属性。

  2. 代码:

         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. 效果:

    image

  4. 说明:对于内建数据库(Sqlite)连接名称为null。

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