You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS中通过托管身份使用TypeORM连接MSSQL数据库?

TypeORM 托管身份连接 MSSQL 及 Repository 初始化问题解答

1. 通过Azure App Service托管身份连接MSSQL

TypeORM的MSSQL适配基于tedious驱动,可直接将Azure托管身份的认证逻辑整合到TypeOrmModuleOptions中。你需要移除原配置里的username和password字段,添加authentication和options配置块,修改后的代码如下:

createTypeOrmOptions(): TypeOrmModuleOptions {
    return {
        name: 'default',
        type: 'mssql',
        host: this.configService.get<string>("DATABASE_HOST"),
        port: Number(this.configService.get<number>("DATABASE_PORT")),
        database: this.configService.get<string>("DATABASE_DB"),
        synchronize: false,
        logging: true,
        // 新增托管身份认证配置
        authentication: {
            type: 'azure-active-directory-msi-app-service'
        },
        options: {
            encrypt: true
        }
    };
}

注意:请确保你的typeorm和tedious依赖是最新版本,旧版本可能不支持该Azure AD认证类型。

2. 初始化Repository时指定数据库连接对象

TypeORM支持明确指定连接来初始化Repository,有两种常见方式:

  • 直接在getRepository中传入连接名称:
    import { getRepository } from 'typeorm';
    import { YourEntity } from './your.entity';
    
    // 使用名为'default'的连接初始化Repository
    const yourRepo = getRepository(YourEntity, 'default');
    
  • 通过已获取的连接实例获取Repository:
    import { getConnection } from 'typeorm';
    import { YourEntity } from './your.entity';
    
    const targetConnection = getConnection('default');
    const yourRepo = targetConnection.getRepository(YourEntity);
    

这两种方式都能确保你使用指定的数据库连接对应的Repository。

内容的提问来源于stack exchange,提问作者user3409127

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 10:51:17