Интеграции объектно-реляционного отображения с GitHub Copilot

GitHub Copilot и расширение MSSQL работают со всеми основными объектно-реляционными фреймворками (ORM) для SQL Server и База данных SQL Azure. Этот справочник охватывает поддерживаемые ORM, возможности каждого из них, а также сквозной пример, который ведёт вас от таблицы SQL Server к типизированной модели, миграции и методу доступа к данным.

Основные итоги

  • GitHub Copilot генерирует модели, миграции и код доступа к данным, адаптированный под выбранный вами ORM.
  • @mssql Участник чата читает вашу схему базы данных и использует её как контекст при генерации ORM-кода.
  • Пользовательские инструкции могут навязывать конвенции как на уровнях Transact-SQL (T-SQL), так и на уровне ORM.

Матрица поддержки ORM

ORM Stack Models Migrations Схема-первая Подход с кодом в первую очередь
Entity Framework Core .NET и C# Yes Yes Yes Yes
Prisma Node.js / TypeScript Yes Yes Yes Yes
Сиквелизация Node.js Yes Yes Yes Yes
SQLAlchemy Python Yes Да (через Alembic) Yes Yes
Джанго ORM Python Yes Yes Yes Limited
TypeORM Node.js / TypeScript Yes Yes Yes Yes
Морось. Node.js / TypeScript Yes Yes Yes Yes
Dapper .NET и C# Micro-ORM Manual нет Yes

Сценарий от начала до конца

Каждый раздел использует один и тот же сценарий: SalesLT.Customer в SQL Server вы хотите добавить email столбц, сгенерировать типизированную модель и создать метод доступа к данным.

Entity Framework Core (платформа для работы с базами данных)

1. Сгенерировать модель

@mssql Generate an Entity Framework Core entity class for
SalesLT.Customer. Use C# records where appropriate. Target
Entity Framework Core 9 with SQL Server provider.

2. Генерировать миграцию

@mssql Generate an Entity Framework Core migration to add an
`Email` column (nvarchar(256), nullable) to the Customer entity.
Use the EF Core Add-Migration conventions and include both the
Up and Down methods.

3. Генерировать метод доступа к данным

@mssql Write a CustomerRepository method that returns all active
customers ordered by LastName. Use the DbContext pattern, async/await,
and return IReadOnlyList<Customer>.

Prisma

1. Сгенерировать модель схемы

@mssql Generate a Prisma model for SalesLT.Customer using the
sqlserver provider. Use @map annotations to match the existing
column names. Set the primary key and unique constraints explicitly.

2. Генерировать миграцию

@mssql Generate a Prisma migration SQL file to add an `email`
column (NVARCHAR(256), nullable) to the SalesLT.Customer table,
compatible with the sqlserver provider.

3. Генерировать метод доступа к данным

@mssql Write a TypeScript function that uses the Prisma client to
return all active customers ordered by last name, including strict
TypeScript types.

Сиквелизация

1. Сгенерировать модель

@mssql Generate a Sequelize model class for SalesLT.Customer using
the sequelize-typescript decorators pattern. Include data type
mappings for DATETIME2 and NVARCHAR columns.

2. Генерировать миграцию

@mssql Generate a Sequelize migration in JavaScript to add an
`email` column (STRING(256), nullable) to the `Customer` table in
the `SalesLT` schema.

3. Генерировать метод доступа к данным

@mssql Write a Sequelize repository method using async/await that
returns all active customers ordered by LastName. Use model scopes
for the `active` filter.

SQLAlchemy

1. Сгенерировать модель

@mssql Generate a SQLAlchemy 2.0 model for SalesLT.Customer using
the declarative Mapped[] syntax. Use the pyodbc driver connection
string format for SQL Server.

2. Генерировать алембическую миграцию

@mssql Generate an Alembic migration script to add an `email`
column (NVARCHAR(256), nullable) to the SalesLT.Customer table.
Include both upgrade and downgrade functions.

3. Генерировать метод доступа к данным

@mssql Write a SQLAlchemy 2.0 async repository method using
select() and scalars() that returns all active customers ordered
by last name.

Джанго ORM

1. Сгенерировать модель

@mssql Generate a Django model for SalesLT.Customer using
django-mssql-backend. Include Meta.db_table to map to the
existing table name with the SalesLT schema.

2. Генерировать миграцию

@mssql Generate a Django migration to add an `email` field
(CharField, max_length=256, null=True) to the Customer model.
Use the AddField operation.

3. Генерировать метод доступа к данным

@mssql Write a Django queryset manager method that returns all
active customers ordered by last_name, using select_related for
any foreign key fields.

TypeORM

1. Сгенерировать сущность

@mssql Generate a TypeORM entity class for SalesLT.Customer.
Use decorators for @Entity, @Column, @PrimaryGeneratedColumn.
Include DATETIME2 and NVARCHAR mappings for SQL Server.

2. Генерировать миграцию

@mssql Generate a TypeORM migration class to add an `email`
column (nvarchar 256, nullable) to the SalesLT.Customer table.
Include both up and down methods.

3. Генерировать метод доступа к данным

@mssql Write a TypeORM repository method that uses the query
builder to return all active customers ordered by last name.
Include strict TypeScript types.

Морось.

1. Сгенерировать схему

@mssql Generate a Drizzle schema definition for SalesLT.Customer
using the mssql dialect. Include type-safe column mappings for
nvarchar, datetime2, and bit types.

2. Генерировать миграцию

@mssql Generate a Drizzle migration SQL file to add an `email`
column (nvarchar 256, nullable) to the SalesLT.Customer table.

3. Генерировать метод доступа к данным

@mssql Write a Drizzle query using the query builder that returns
all active customers ordered by last name. Use type-safe column
references.

Dapper

Dapper — это микро-ORM без поддержки генерации схем или миграции, но GitHub Copilot может генерировать методы доступа к данным, использующие методы расширения Dapper против существующей схемы.

@mssql Write a Dapper-based repository method in C# that returns
all active customers ordered by LastName. Use parameterized
queries and a typed Customer record.

Распространённые закономерности и оговорки

  • Entity Framework Core + сбор SQL Server. Для сравнений, чувствительных к регистру, явно задайте EF.Functions.Collate запросы. Не предполагайте, что стандартная система сортировки соответствует серверным настройкам SQL Server.
  • Prisma + MSSQL строка подключения quoting. Строки подключения База данных SQL Azure требуют тщательного кодирования URL специальных символов в паролях. См. документацию провайдера Prisma SQL Server.
  • Драйвер SQLAlchemy + pyodbc. Установите и скажите правильную версию драйвера (ODBC Driver 18 for SQL Server по состоянию на 2026 год). Прикрепляйте версии requirements.txt , чтобы избежать сюрпризов.
  • Django ORM + первичное отображение клавиш. IDENTITY Столбцы требуют упаковки django-mssql-backend и IDENTITY_INSERT обработки данных для загрузки данных.
  • TypeORM + CamelCase. Устанавливайте entityPrefix и используйте стратегии именования, чтобы они соответствовали вашим индивидуальным инструкциям , если ваша команда использует определённую конвенцию.

Оставьте свой отзыв

Чтобы помочь нам уточнить и улучшить GitHub Copilot для расширения MSSQL, используйте следующий шаблон проблемы GitHub для отправки отзывов: GitHub Copilot Feedback

При отправке отзывов рассмотрите возможность включения:

  • Тестируемые сценарии: сообщите нам, на какие области вы ориентированы, например создание схемы, создание запросов, безопасность, локализация.

  • Что хорошо работало: Опишите любые ситуации, которые были безупречными, полезными или превысили ваши ожидания.

  • Проблемы или ошибки: любые проблемы, несоответствия или запутанное поведение. Снимки экрана или записи экрана особенно полезны.

  • Предложения по улучшению: поделитесь идеями для улучшения удобства использования, расширения охвата или улучшения ответов GitHub Copilot.