Консоль диспетчера пакетов visual studio команды
Installing the tools
Install the Package Manager Console tools by running the following command in Package Manager Console:
Update the tools by running the following command in Package Manager Console.
Verify the installation
Verify that the tools are installed by running this command:
The output looks like this (it doesn't tell you which version of the tools you're using):
Using the tools
Before using the tools:
Target and startup project
The commands refer to a project and a startup project.
The project is also known as the target project because it's where the commands add or remove files. By default, the Default project selected in Package Manager Console is the target project. You can specify a different project as target project by using the parameter.
The startup project is the one that the tools build and run. The tools have to execute application code at design time to get information about the project, such as the database connection string and the configuration of the model. By default, the Startup Project in Solution Explorer is the startup project. You can specify a different project as startup project by using the parameter.
The startup project and target project are often the same project. A typical scenario where they are separate projects is when:
Other target frameworks
Starting in EF Core 5.0, additional arguments can also be passed into Program.CreateHostBuilder allowing you to specify the environment on the command-line:
Common parameters
The following table shows parameters that are common to all of the EF Core commands:
Parameter | Description |
---|---|
The DbContext class to use. Class name only or fully qualified with namespaces. If this parameter is omitted, EF Core finds the context class. If there are multiple context classes, this parameter is required. | |
The target project. If this parameter is omitted, the Default project for Package Manager Console is used as the target project. | |
The startup project. If this parameter is omitted, the Startup project in Solution properties is used as the target project. | |
Arguments passed to the application. Added in EF Core 5.0. | |
-Verbose | Show verbose output. |
To show help information about a command, use PowerShell's Get-Help command.
The Context , Project , and StartupProject parameters support tab-expansion.
Add-Migration
Adds a new migration.
Parameter | Description |
---|---|
The name of the migration. This is a positional parameter and is required. | |
The directory use to output the files. Paths are relative to the target project directory. Defaults to "Migrations". | |
The namespace to use for the generated classes. Defaults to generated from the output directory. Added in EF Core 5.0. |
The common parameters are listed above.
Bundle-Migration
Creates an executable to update the database.
The common parameters are listed above.
Drop-Database
Drops the database.
Parameter | Description |
---|---|
Show which database would be dropped, but don't drop it. |
The common parameters are listed above.
Get-DbContext
Lists and gets information about available DbContext types.
The common parameters are listed above.
Get-Migration
Lists available migrations. Added in EF Core 5.0.
Parameter | Description |
---|---|
The connection string to the database. Defaults to the one specified in AddDbContext or OnConfiguring. | |
Don't connect to the database. |
The common parameters are listed above.
Optimize-DbContext
Generates a compiled version of the model used by the DbContext . Added in EF Core 6.
See Compiled models for more information.
Parameter | Description |
---|---|
The directory to put files in. Paths are relative to the project directory. | |
The namespace to use for all generated classes. Defaults to generated from the root namespace and the output directory plus CompiledModels . |
The common parameters are listed above.
The following example uses the defaults and works if there is only one DbContext in the project:
The following example optimizes the model for the context with the specified name and places it in a separate folder and namespace:
Remove-Migration
Removes the last migration (rolls back the code changes that were done for the migration).
Parameter | Description |
---|---|
Revert the migration (roll back the changes that were applied to the database). |
The common parameters are listed above.
Scaffold-DbContext
Generates code for a DbContext and entity types for a database. In order for Scaffold-DbContext to generate an entity type, the database table must have a primary key.
The common parameters are listed above.
Example that scaffolds only selected tables and creates the context in a separate folder with a specified name and namespace:
The following example reads the connection string from the project's configuration possibly set using the Secret Manager tool.
Script-DbContext
Generates a SQL script from the DbContext. Bypasses any migrations.
Parameter | Description |
---|---|
The file to write the result to. |
The common parameters are listed above.
Script-Migration
Generates a SQL script that applies all of the changes from one selected migration to another selected migration.
Parameter | Description |
---|---|
The starting migration. Migrations may be identified by name or by ID. The number 0 is a special case that means before the first migration. Defaults to 0. | |
The ending migration. Defaults to the last migration. | |
Generate a script that can be used on a database at any migration. | |
Don't generate SQL transaction statements. Added in EF Core 5.0. | |
The file to write the result to. IF this parameter is omitted, the file is created with a generated name in the same folder as the app's runtime files are created, for example: /obj/Debug/netcoreapp2.1/ghbkztfz.sql/. |
The common parameters are listed above.
The To , From , and Output parameters support tab-expansion.
The following example creates a script for the InitialCreate migration (from a database without any migrations), using the migration name.
The following example creates a script for all migrations after the InitialCreate migration, using the migration ID.
Update-Database
Updates the database to the last migration or to a specified migration.
Parameter | Description |
---|---|
The target migration. Migrations may be identified by name or by ID. The number 0 is a special case that means before the first migration and causes all migrations to be reverted. If no migration is specified, the command defaults to the last migration. | |
The connection string to the database. Defaults to the one specified in AddDbContext or OnConfiguring . Added in EF Core 5.0. |
The common parameters are listed above.
The Migration parameter supports tab-expansion.
The following example reverts all migrations.
The following examples update the database to a specified migration. The first uses the migration name and the second uses the migration ID and a specified connection:
The NuGet Package Manager Console lets you use NuGet PowerShell commands to find, install, uninstall, and update NuGet packages. Using the console is necessary in cases where the Package Manager UI does not provide a way to perform an operation. To use nuget.exe CLI commands in the console, see Using the nuget.exe CLI in the console.
The console is built into Visual Studio on Windows. It is not included with Visual Studio for Mac or Visual Studio Code.
The commands listed here are specific to the Package Manager Console in Visual Studio, and differ from the Package Management module commands that are available in a general PowerShell environment. Specifically, each environment has commands that are not available in the other, and commands with the same name may also differ in their specific arguments. When using the Package Management Console in Visual Studio, the commands and arguments documented in this present topic apply.
Find and install a package
For example, finding and installing a package is done with three easy steps:
Open the project/solution in Visual Studio, and open the console using the Tools > NuGet Package Manager > Package Manager Console command.
Find the package you want to install. If you already know this, skip to step 3.
Run the install command:
All operations that are available in the console can also be done with the NuGet CLI. However, console commands operate within the context of Visual Studio and a saved project/solution and often accomplish more than their equivalent CLI commands. For example, installing a package through the console adds a reference to the project whereas the CLI command does not. For this reason, developers working in Visual Studio typically prefer using the console to the CLI.
Many console operations depend on having a solution opened in Visual Studio with a known path name. If you have an unsaved solution, or no solution, you can see the error, "Solution is not opened or not saved. Please ensure you have an open and saved solution." This indicates that the console cannot determine the solution folder. Saving an unsaved solution, or creating and saving a solution if you don't have one open, should correct the error.
Opening the console and console controls
Open the console in Visual Studio using the Tools > NuGet Package Manager > Package Manager Console command. The console is a Visual Studio window that can be arranged and positioned however you like (see Customize window layouts in Visual Studio).
By default, console commands operate against a specific package source and project as set in the control at the top of the window:
Selecting a different package source and/or project changes those defaults for subsequent commands. To overrride these settings without changing the defaults, most commands support -Source and -ProjectName options.
To manage package sources, select the gear icon. This is a shortcut to the Tools > Options > NuGet Package Manager > Package Sources dialog box as described on the Package Manager UI page. Also, the control to the right of the project selector clears the console's contents:
Install a package
Installing a package in the console performs the same steps as described on What happens when a package is installed, with the following additions:
- The Console displays applicable license terms in its window with implied agreement. If you do not agree to the terms, you should uninstall the package immediately.
- Also a reference to the package is added to the project file and appears in Solution Explorer under the References node, you need to save the project to see the changes in the project file directly.
Uninstall a package
See Uninstall-Package. Use Get-Package to see all packages currently installed in the default project if you need to find an identifier.
Uninstalling a package performs the following actions:
- Removes references to the package from the project (and whatever management format is in use). References no longer appear in Solution Explorer. (You might need to rebuild the project to see it removed from the Bin folder.)
- Reverses any changes made to app.config or web.config when the package was installed.
- Removes previously-installed dependencies if no remaining packages use those dependencies.
Update a package
Find a package
See Find-Package. In Visual Studio 2013 and earlier, use Get-Package instead.
Availability of the console
The Package Manager Console is not presently available with Visual Studio for Mac. The equivalent commands, however, are available through the NuGet CLI. Visual Studio for Mac does have a UI for managing NuGet packages. See Including a NuGet package in your project.
The Package Manager Console is not included with Visual Studio Code.
Extend the Package Manager Console
Set up a NuGet PowerShell profile
A PowerShell profile lets you make commonly-used commands available wherever you use PowerShell. NuGet supports a NuGet-specific profile typically found at the following location:
To find the profile, type $profile in the console:
Use the nuget.exe CLI in the console
Установка инструментов
установите средства консоли диспетчер пакетов, выполнив следующую команду в консоли диспетчер пакетов.
обновите средства, выполнив следующую команду в консоли диспетчер пакетов.
Проверка установки
Убедитесь, что средства установлены, выполнив следующую команду:
Выходные данные выглядят следующим образом (он не указывает, какую версию инструментов вы используете):
Использование средств
Перед использованием средств:
Целевой и запускаемый проекты
Команды ссылаются на проект и запускаемый проект.
Проект также называется целевым проектом , так как он служит для добавления или удаления файлов. по умолчанию проект по умолчанию , выбранный в консоли диспетчер пакетов , является целевым. Можно указать другой проект в качестве целевого проекта с помощью параметра.
Запускаемый проект — это тот, который выполняет сборка и запуск средств. Средства должны выполнять код приложения во время разработки для получения сведений о проекте, таких как строка подключения к базе данных и Конфигурация модели. по умолчанию Project запуска в Обозреватель решений является запускаемым проектом. Можно указать другой проект в качестве запускаемого проекта с помощью параметра.
Запускаемый проект и целевой проект часто являются одним и тем же проектом. Типичный сценарий, в котором они являются отдельными проектами, состоит в следующих случаях:
Другие целевые платформы
Начиная с EF Core 5,0, дополнительные аргументы также могут передаваться в Program. Креатехостбуилдер, что позволяет указать среду в командной строке:
Общие параметры
В следующей таблице приведены параметры, которые являются общими для всех EF Coreных команд.
Параметр | Описание |
---|---|
Класс DbContext для использования. Только имя класса или полный квалификатор с пространствами имен. Если этот параметр опущен, EF Core находит класс контекста. Если имеется несколько классов контекста, этот параметр является обязательным. | |
Целевой проект. если этот параметр не указан, в качестве целевого проекта используется проект по умолчанию для диспетчер пакетов консоли . | |
Автоматически запускаемый проект. Если этот параметр не указан, в качестве целевого проекта используется запускаемый проект в свойствах решения . | |
Аргументы, передаваемые в приложение. Добавлено в EF Core 5,0. | |
-Verbose | Отображение подробных выходных данных. |
Чтобы отобразить справочные сведения о команде, используйте команду PowerShell Get-Help .
Context Параметры, Project и StartupProject поддерживают расширение клавишей TAB.
Add-Migration
Добавляет новый перенос.
Параметр | Описание |
---|---|
Имя миграции. Этот параметр является позиционированным и является обязательным. | |
Каталог используется для вывода файлов. Пути задаются относительно целевого каталога проекта. По умолчанию используется значение "миграции". | |
Пространство имен, используемое для создаваемых классов. По умолчанию создается из выходного каталога. Добавлено в EF Core 5,0. |
Bundle-Migration
Создает исполняемый файл для обновления базы данных.
Drop-Database
Удаляет базу данных.
Параметр | Описание |
---|---|
Показывает, какую базу данных следует удалить, но не удалять. |
Get-DbContext
Перечисляет и получает сведения о доступных DbContext типах.
Get-Migration
Список доступных миграций. Добавлено в EF Core 5,0.
Параметр | Описание |
---|---|
Строка подключения к базе данных. По умолчанию используется значение, указанное в AddDbContext или onconfiguring. | |
Не подключайтесь к базе данных. |
Optimize-DbContext
Создает скомпилированную версию модели, DbContext используемую. Добавлено в EF Core 6.
Дополнительные сведения см. в разделе скомпилированные модели .
Параметр | Описание |
---|---|
Каталог для размещения файлов. Пути задаются относительно каталога проекта. | |
Пространство имен, используемое для всех создаваемых классов. По умолчанию создается из корневого пространства имен и выходного каталога плюс CompiledModels . |
В следующем примере используются значения по умолчанию и работает, если в проекте имеется только один DbContext .
В следующем примере модель оптимизируется для контекста с указанным именем и помещается в отдельную папку и пространство имен:
Remove-Migration
Удаляет последнюю миграцию (выполняет откат изменений кода, выполненных для миграции).
Параметр | Описание |
---|---|
Отмените миграцию (выполните откат изменений, примененных к базе данных). |
Scaffold-DbContext
Создает код для DbContext типов сущностей и для базы данных. Scaffold-DbContext Чтобы создать тип сущности, таблица базы данных должна иметь первичный ключ.
Пример: формирование шаблонов только для выбранных таблиц и создание контекста в отдельной папке с указанным именем и пространством имен.
В следующем примере считывается строка подключения из конфигурации проекта, которая может быть задана с помощью средства диспетчера секретов.
Script-DbContext
создает скрипт SQL из DbContext. Обход всех миграций.
Параметр | Описание |
---|---|
Файл, в который записывается результат. |
Script-Migration
создает скрипт SQL, который применяет все изменения из одной выбранной миграции к другой выбранной миграции.
Параметр | Описание |
---|---|
Начало миграции. Миграция может быть идентифицирована по имени или по ИДЕНТИФИКАТОРу. Число 0 — это особый случай, который означает перед первой миграцией. Значение по умолчанию — 0. | |
Завершение миграции. По умолчанию используется последняя миграция. | |
Создание скрипта, который может использоваться в базе данных при любой миграции. | |
не создавайте инструкции SQL transaction. Добавлено в EF Core 5,0. | |
Файл, в который записывается результат. Если этот параметр не указан, файл создается с именем, созданным в той же папке, что и файлы среды выполнения приложения, например: /obj/Debug/netcoreapp2.1/ghbkztfz.SQL/. |
To Параметры, From и Output поддерживают расширение клавишей TAB.
В следующем примере создается скрипт для миграции InitialCreate (из базы данных без каких-либо миграций) с использованием имени миграции.
В следующем примере создается скрипт для всех миграций после миграции InitialCreate с использованием идентификатора миграции.
Update-Database
Обновляет базу данных до последней миграции или до указанной миграции.
Параметр | Описание |
---|---|
Целевая миграция. Миграция может быть идентифицирована по имени или по ИДЕНТИФИКАТОРу. Число 0 — это особый случай, который означает перед первой миграцией и приводит к отмене всех миграций. Если миграция не указана, команда по умолчанию принимает значение последней миграции. | |
Строка подключения к базе данных. По умолчанию используется значение, заданное в AddDbContext или OnConfiguring . Добавлено в EF Core 5,0. |
Migration Параметр поддерживает расширение клавиш TAB.
В следующем примере возвращаются все миграции.
В следующих примерах база данных обновляется до указанной миграции. В первом случае используется имя миграции, а во втором используется идентификатор миграции и указанное соединение:
The Package Manager Console provides a PowerShell interface within Visual Studio on Windows to interact with NuGet through the specific commands listed below. (The console is not presently available in Visual Studio for Mac.) For a guide to using the console, see Install and manage packages using Package Manager Console topic.
All PowerShell commands relate only to package consumption. No PowerShell commands relate to creating and publishing packages except to the extent that a package can also be a consumer of other packages.
The commands listed here are specific to the Package Manager Console in Visual Studio, and differ from the Package Management module commands that are available in a general PowerShell environment. Specifically, each environment has commands that are not available in the other, and commands with the same name may also differ in their specific arguments. When using the Package Management Console in Visual Studio, the commands and arguments documented in this present topic apply.
Common Commands | Description | NuGet Version |
---|---|---|
Install-Package | Installs a package and its dependencies into the project. | All |
Update-Package | Updates a package and its dependencies, or all packages in a project. | All |
Find-Package | Searches a package source using a package ID or keywords. | 3.0+ |
Get-Package | Retrieves the list of packages installed in the local repository, or lists packages available from a package source. | All |
Secondary Commands | Description | NuGet Version |
---|---|---|
Add-BindingRedirect | Examines all assemblies within the output path for a project and adds binding redirects to the app.config or web.config where necessary. | All |
Get-Project | Displays information about the default or specified project. | 3.0+ |
Open-PackagePage | Launches the default browser with the project, license, or report abuse URL for the specified package. | Deprecated in 3.0+ |
Register-TabExpansion | Registers a tab expansion for the parameters of a command, allowing you to create customized expansions for commonly-used parameter values. | All |
Sync-Package | Get the version of installed package from specified project and syncs the version to the rest of projects in the solution. | 3.0+ |
Uninstall-Package | Removes a package from a project, optionally removing its dependencies. | All |
For complete, detailed help on any of these commands within the console, just run the following with the command name in question:
All Package Manager Console commands support the following common PowerShell parameters:
- Debug
- ErrorAction
- ErrorVariable
- OutBuffer
- OutVariable
- PipelineVariable
- Verbose
- WarningAction
- WarningVariable
For details, refer to about_CommonParameters in the PowerShell documentation.
Консоль диспетчера пакетов NuGet позволяет использовать команды PowerShell NuGet для поиска, установки, удаления и обновления пакетов NuGet. Это удобно, когда пользовательский интерфейс диспетчера пакетов не позволяет выполнять операции. См. подробнее об nuget.exe .
Консоль встроена в Visual Studio для Windows. Она не включена в Visual Studio для Mac и Visual Studio Code.
Перечисленные здесь команды относятся только к консоли диспетчера пакетов в Visual Studio и отличаются от команд модуля "Управление пакетами", доступных в общей среде PowerShell. В частности, в каждой среде есть команды, недоступные в другой среде, а в командах с тем же именем могут отличаться некоторые аргументы. При использовании консоли "Управление пакетами" в Visual Studio применяются команды и аргументы, описанные в этой статье.
Поиск и установка пакета
Для поиска и установки пакета необходимо выполнить три простых шага:
Откройте проект или решение в Visual Studio, а затем откройте консоль с помощью команды Средства Диспетчер пакетов NuGet > Консоль диспетчера пакетов.
Найдите пакет, который требуется установить. Если вы уже знакомы с этим процессом, перейдите к шагу 3.
Выполните команду установки:
Все операции, доступные в консоли, также можно выполнить с помощью CLI NuGet. Но команды консоли работают в контексте Visual Studio и сохраненного проекта или решения, и область их применения часто шире, чем у их эквивалентов в CLI. Например, при установке пакета с помощью консоли добавляется ссылка на проект, а при использовании команды CLI этого не происходит. По этой причине разработчики, работающие в Visual Studio, обычно предпочитают использовать консоль вместо CLI.
Открытие консоли и элементов управления консоли
Откройте консоль в Visual Studio с помощью команды Средства Диспетчер пакетов NuGet > Консоль диспетчера пакетов. Консоль — это окно Visual Studio, которое может быть упорядочено и размещено по вашему усмотрению (см. руководство по настройке макетов окон в Visual Studio).
По умолчанию команды консоли работают с конкретным источником пакета и проектом, как указано в элементе управления в верхней части окна.
Выбор другого источника пакета или проекта изменяет эти значения по умолчанию для последующих команд. Чтобы переопределить эти настройки, не меняя значения по умолчанию, большинство команд поддерживают параметры -Source и -ProjectName .
Чтобы управлять источниками пакетов, щелкните значок шестеренки. Это ярлык для диалогового окна Средства Параметры > Диспетчер пакетов NuGet > Источники пакетов, как описано на странице >. Кроме того, элемент управления справа от средства выбора проектов очищает содержимое консоли.
Установка пакета
При установке пакета в консоли выполняются те же действия, которые описаны в руководстве по установке пакета NuGet, со следующими дополнениями:
- Консоль отображает применимые условия лицензии в окне с соответствующим соглашением. Если вы не согласны с условиями, следует сразу же удалить пакет.
- Кроме того, ссылка на пакет добавляется в файл проекта и отображается в обозревателе решений в узле Ссылки. Сохраните проект, чтобы просмотреть изменения непосредственно в файле проекта.
Удаление пакета
См. подробнее об Uninstall-Package. Если необходимо найти идентификатор, чтобы просмотреть все пакеты, установленные в проекте по умолчанию, используйте команду Get-Package.
При удалении пакета выполняются следующие действия:
- Удаляются ссылки на пакет из проекта (и любого используемого формата управления). Ссылки больше не отображаются в обозревателе решений (возможно, потребуется перестроить проект, чтобы он был удален из папки Bin).
- Отменяются все изменения, внесенные в app.config или web.config при установке пакета.
- Удаляются ранее установленные зависимости, если остальные пакеты не используют эти зависимости.
Обновление пакета
Поиск пакета
См. подробнее о Find-Package. В Visual Studio 2013 и более ранних версиях используйте команду Get-Package.
Доступность консоли
Консоль диспетчера пакетов сейчас недоступна в Visual Studio для Mac. Но аналогичные команды доступны через CLI NuGet. В Visual Studio для Mac есть пользовательский интерфейс для управления пакетами NuGet. См. подробнее о включении пакета NuGet в проект.
Консоль диспетчера пакетов не входит в Visual Studio Code.
Расширение консоли диспетчера пакетов
Настройка профиля PowerShell NuGet
Профиль PowerShell позволяет сделать часто используемые команды доступными при использовании PowerShell. NuGet поддерживает профиль NuGet, который обычно находится в следующем расположении:
Чтобы найти профиль, в консоли введите $profile .
Использование CLI nuget.exe в консоли
Читайте также: