Condividi tramite


Avvio rapido: Generare codice

In questa guida introduttiva si apprenderà come GitHub Copilot accelera lo sviluppo di SQL e ORM (Object-Relational Mapping) generando codice compatibile con il contesto direttamente all'interno di Visual Studio Code. GitHub Copilot consente di eseguire lo scaffolding di tabelle, sviluppare schemi e ridurre gli script ripetitivi. Che si usi T-SQL o si usino ORM come Entity Framework, Sequelize, Prisma o SQLAlchemy, GitHub Copilot consente di concentrarsi sulla creazione della logica dell'applicazione.

Inizia subito

Assicurarsi di essere connessi a un database e di aprire una finestra dell'editor attivo con l'estensione MSSQL. Questa connessione consente al partecipante della @mssql chat di comprendere il contesto dell'ambiente di database, abilitando suggerimenti accurati e con riconoscimento del contesto. Senza una connessione al database, il partecipante della chat non avrà lo schema o il contesto dei dati per fornire risposte significative.

Gli esempi seguenti usano il AdventureWorksLT2022 database di esempio, che è possibile scaricare dalla home page degli esempi di Microsoft SQL Server e dei progetti della community .

Per ottenere risultati ottimali, modificare i nomi di tabella e schema in modo che corrispondano al proprio ambiente.

Assicurarsi che la chat includa il @mssql prefisso. Ad esempio, digitare @mssql seguito dalla domanda o dal prompt. Ciò garantisce che il partecipante della chat comprenda che si sta chiedendo assistenza correlata a SQL.

Generazione di codice con GitHub Copilot

Usare GitHub Copilot per generare codice compatibile con SQL e ORM che riflette la struttura del database connesso e segue le procedure consigliate. Dalla definizione di tabelle e relazioni alle viste di scripting, alla creazione di file di migrazione o allo scaffolding dei livelli di accesso ai dati e alle API, GitHub Copilot consente di spostarsi più velocemente e con maggiore attendibilità.

Di seguito sono riportati casi d'uso comuni ed esempi di ciò che è possibile chiedere tramite il partecipante alla chat:

Generare codice SQL

GitHub Copilot consente di generare codice SQL per diversi scenari di sviluppo, dallo scripting, alla creazione e alla modifica di tabelle alla scrittura di stored procedure e viste. Questi esempi illustrano come usare GitHub Copilot per automatizzare gli script SQL ripetitivi e seguire le procedure consigliate per lo sviluppo T-SQL.

Scrivere tutte le tabelle in uno schema

Script out all the tables in the `SalesLT` schema as `CREATE TABLE` statements in SQL.

Recuperare i dati dei clienti con una procedura memorizzata

Write a SQL stored procedure in my current database. The procedure should retrieve all customers from the `SalesLT.Customer` table where the `LastName` matches a given parameter. Make sure to use T-SQL best practices.

Creare uno script per una tabella con tutti i vincoli e gli indici

Script out the `SalesLT.Customer` table as a `CREATE TABLE` statement, including all constraints and indexes.

Creare uno script per una vista che unisce due tabelle

Generate a SQL script to create a view that joins the `SalesLT.Customer` and `SalesLT.SalesOrderHeader` tables, showing customer names and their total order amounts.

Modificare una tabella aggiungendo una nuova colonna

Write a SQL script to alter the `SalesLT.Customer` table by adding a `last_updated` column with a default timestamp.

Generare migrazioni ORM

GitHub Copilot può generare migrazioni e definizioni di modelli compatibili con ORM in base al contesto dello schema e al framework scelto. Da Sequelize a Entity Framework, Prisma e SQLAlchemy, GitHub Copilot consente di eseguire lo scaffolding delle modifiche allineate al modello di dati dell'applicazione.

Generare un modello per aggiungere una colonna

Generate a Sequelize (JavaScript) model to add an `email` column (`varchar(256)`) to the `SalesLT.Customer` table.

Generare la classe del modello Entity Framework

Generate an Entity Framework model class in C# to represent a `SalesLT.ProductModel` table with `id`, `name`, and `description` columns.

Generare un modello di Entity Framework

Generate an Entity Framework model in C# based on the existing `SalesLT.Product` table.

Scrivere codice Python per definire una tabella

Write SQLAlchemy code to define a `SalesLT.OrderDetails` table with `id`, `order_date`, and `customer_id` fields, ensuring compatibility with `Python`.

Scrivere una query con parametri

Using SQLAlchemy, write a parameterized query that retrieves all customers from the `SalesLT.Customer` table where the `LastName` matches a provided parameter.

Aggiornare il modello esistente per aggiungere una tabella

Update my existing Prisma model (schema.prisma) to define a new `SalesLT.Order` model with `id`, `customer_id`, and `order_date` fields.

Generare una classe modello per una tabella

Generate a SQLAlchemy model class for the `SalesLT.Product` table, including columns and data types.

Generare il codice dell'app boilerplate

GitHub Copilot consente anche di eseguire lo scaffolding di componenti back-end e front-end che interagiscono con il database SQL. Questi esempi illustrano come passare dallo schema al codice dell'applicazione funzionante usando stack comuni come Funzioni di Azure, Node.js, Django e Next.js.

Integrazioni serverless backend SQL e Blazor

L'esempio seguente mostra i prompt completi che è possibile usare con GitHub Copilot Chat per eseguire lo scaffolding di una soluzione end-to-end. Questi prompt includono istruzioni dettagliate e contesto per consentire a Copilot di generare codice accurato e strutturato nei livelli back-end e front-end.

Generate a full-stack app using Azure SQL bindings for Functions and Blazor WebAssembly. Follow these steps:

1. Backend: Azure Functions (C#) with SQL Bindings

   - Configure SQL Bindings to automatically read and write data from the `SalesLT.Customer` table.
   - Implement HTTP-triggered functions with the following endpoints:
     - `GET /api/customers` – Fetch all customers.
     - `GET /api/customers/{id}` – Get a specific customer by ID.
     - `POST /api/customers` – Create a new customer.
     - `PUT /api/customers/{id}` – Update an existing customer.
     - `DELETE /api/customers/{id}` – Delete a customer.
   - Use `Dependency Injection` for database connections and logging.
   - Include an `appsettings.json` file to store database connection strings and environment variables.
   - Use `Azure Functions Core Tools` to run and test the functions locally.

1. Frontend: Blazor WebAssembly (Optional)

   - Create a Blazor WebAssembly frontend that consumes the API.
   - Display a table with customer data and a form to add new customers.
   - Use `HttpClient` to call the Azure Functions endpoints.
   - Implement two-way data binding to handle form inputs dynamically.
   - Use Bootstrap or Blazor components for styling and layout.

Ensure the project includes setup instructions for running both the Azure Functions backend and Blazor WebAssembly frontend locally, with proper `.env` or `local.settings.json` configurations for database connections.

Stack completo con Node.js e Next.js

L'esempio seguente è un prompt dettagliato che è possibile fornire in GitHub Copilot Chat per generare la configurazione back-end completa, incluse le route API e l'integrazione del database.

Generate a REST API using Node.js with Express that connects to my local SQL Database. Use the Tedious package for SQL Server connections and Prisma as the ORM. Follow these steps:

1. Backend: Node.js + Express

   - Establish a database connection using Prisma with Tedious as the SQL Server driver.
   - Implement API routes for `SalesLT.Customer` with the following endpoints:
     - `GET /customers` – Fetch all customers.
     - `GET /customers/:id` – Get a specific customer by ID.
     - `POST /customers` – Create a new customer.
     - `PUT /customers/:id` – Update an existing customer.
     - `DELETE /customers/:id` – Delete a customer.
   - Configure `Prisma` to map the `SalesLT.Customer` table and generate database migrations using `prisma migrate dev`.
   - Use `dotenv` for environment variables (database credentials, ports, etc.).
   - Add `Jest` for testing the API endpoints.

1. Frontend: Next.js + TypeScript (Optional)

   - Create a Next.js frontend that consumes the API.
   - Display a table with customer data and a form to add new customers.
   - Use React hooks (`useState`, `useEffect`) to manage state and fetch data dynamically.
   - Style the UI using Tailwind CSS.
   - Implement server-side data fetching (`getServerSideProps`) in Next.js for improved performance.

Ensure the project includes setup instructions for running both the backend and frontend independently, with proper `.env` configurations for the database connection.

Backend: Django + Framework REST Django

L'esempio seguente è un prompt dettagliato che è possibile fornire in GitHub Copilot Chat per generare la configurazione back-end completa, incluse le route API e l'integrazione del database.

Scaffold a Django backend with Django REST Framework for the `SalesLT.Customer` table. Follow these steps:

- Implement API routes using Django's `ModelViewSet` with the following endpoints:
  - `GET /customers` – Fetch all customers.
  - `GET /customers/{id}` – Get a specific customer by ID.
  - `POST /customers` – Create a new customer.
  - `PUT /customers/{id}` – Update an existing customer.
  - `DELETE /customers/{id}` – Delete a customer.

- Add instructions for generating database migrations with `python manage.py makemigrations` and `migrate`.

Condividere la propria esperienza

Per ottimizzare e migliorare GitHub Copilot per l'estensione MSSQL, usare il modello di problema GitHub seguente per inviare commenti e suggerimenti: Commenti e suggerimenti su GitHub Copilot

Quando si inviano commenti e suggerimenti, è consigliabile includere:

  • Scenari testati: segnalare le aree su cui ci si è concentrati, ad esempio la creazione dello schema, la generazione di query, la sicurezza, la localizzazione.

  • Cosa ha funzionato bene : descrivere tutte le esperienze che si sono sentite fluide, utili o superate le aspettative.

  • Problemi o bug : includere eventuali problemi, incoerenze o comportamenti confusi. Screenshot o registrazioni dello schermo sono particolarmente utili.

  • Suggerimenti per il miglioramento : condividere idee per migliorare l'usabilità, espandere la copertura o migliorare le risposte di GitHub Copilot.