The command-line interface (CLI) tools for Entity Framework Core perform design-time development tasks. For example, they create migrations, apply migrations, and generate code for a model based on an existing database. The commands are an extension to the cross-platform dotnet command, which is part of the .NET Core SDK. These tools work with .NET Core projects.
If you’re using Visual Studio, we recommend the Package Manager Console tools instead:
- They automatically work with the current project selected in the Package Manager Console without requiring that you manually switch directories.
- They automatically open files generated by a command after the command is completed.
Installing the tools
The installation procedure depends on project type and version:
- EF Core 3.x
- ASP.NET Core version 2.1 and later
- EF Core 2.x
- EF Core 1.x
EF Core 3.x
dotnet ef must be installed as a global or local tool. Most developers will install dotnet ef as a global tool with the following command:
You can also use dotnet ef as local tool. To use it as a local tool, restore the dependencies of a project that declares it as a tooling dependency using a tool manifest file.
Install the .NET Core SDK 3.0). The SDK has to be installed even if you have the latest version of Visual Studio.
Install the latest Microsoft.EntityFrameworkCore.Design package.
ASP.NET Core 2.1+
Install the current .NET Core SDK. The SDK has to be installed even if you have the latest version of Visual Studio 2017.
This is all that is needed for ASP.NET Core 2.1+ because the Microsoft.EntityFrameworkCore.Design package is included in the Microsoft.AspNetCore.App metapackage.
EF Core 2.x (not ASP.NET Core)
The dotnet ef commands are included in the .NET Core SDK, but to enable the commands you have to install the Microsoft.EntityFrameworkCore.Design package.
Install the current .NET Core SDK. The SDK has to be installed even if you have the latest version of Visual Studio.
Install the latest stable Microsoft.EntityFrameworkCore.Design package.
EF Core 1.x
Install the .NET Core SDK version 2.1.200. Later versions are not compatible with CLI tools for EF Core 1.0 and 1.1.
Configure the application to use the 2.1.200 SDK version by modifying its global.json file. This file is normally included in the solution directory (one above the project).
Edit the project file and add Microsoft.EntityFrameworkCore.Tools.DotNet as a DotNetCliToolReference item. Specify the latest 1.x version, for example: 1.1.6. See the project file example at the end of this section.
Install the latest 1.x version of the Microsoft.EntityFrameworkCore.Design package, for example:
With both package references added, the project file looks something like this:
A package reference with PrivateAssets="All" isn’t exposed to projects that reference this project. This restriction is especially useful for packages that are typically only used during development.
Verify installation
Run the following commands to verify that EF Core CLI tools are correctly installed:
The output from the command identifies the version of the tools in use:
Using the tools
Before using the tools, you might have to create a startup project or set the environment.
Target project 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 project in the current directory is the target project. You can specify a different project as target project by using the option.
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 project in the current directory is the startup project. You can specify a different project as startup project by using the option.
The startup project and target project are often the same project. A typical scenario where they are separate projects is when:
- The EF Core context and entity classes are in a .NET Core class library.
- A .NET Core console app or web app references the class library.
Other target frameworks
The CLI tools work with .NET Core projects and .NET Framework projects. Apps that have the EF Core model in a .NET Standard class library might not have a .NET Core or .NET Framework project. For example, this is true of Xamarin and Universal Windows Platform apps. In such cases, you can create a .NET Core console app project whose only purpose is to act as startup project for the tools. The project can be a dummy project with no real code — it is only needed to provide a target for the tooling.
Why is a dummy project required? As mentioned earlier, the tools have to execute application code at design time. To do that, they need to use the .NET Core runtime. When the EF Core model is in a project that targets .NET Core or .NET Framework, the EF Core tools borrow the runtime from the project. They can’t do that if the EF Core model is in a .NET Standard class library. The .NET Standard is not an actual .NET implementation; it’s a specification of a set of APIs that .NET implementations must support. Therefore .NET Standard is not sufficient for the EF Core tools to execute application code. The dummy project you create to use as startup project provides a concrete target platform into which the tools can load the .NET Standard class library.
ASP.NET Core environment
To specify the environment for ASP.NET Core projects, set the ASPNETCORE_ENVIRONMENT environment variable before running commands.
Common options
| Option | Description |
|---|---|
| —json | Show JSON output. |
| —context | The DbContext class to use. Class name only or fully qualified with namespaces. If this option is omitted, EF Core will find the context class. If there are multiple context classes, this option is required. |
| -p | —project |
dotnet ef database drop
Drops the database.
| Option | Description |
|---|---|
| Don’t confirm. | |
| Show which database would be dropped, but don’t drop it. |
dotnet ef database update
Updates the database to the last migration or to a specified migration.
| Argument | 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 following examples update the database to a specified migration. The first uses the migration name and the second uses the migration ID:
dotnet ef dbcontext info
Gets information about a DbContext type.
dotnet ef dbcontext list
Lists available DbContext types.
dotnet ef dbcontext scaffold
Generates code for a DbContext and entity types for a database. In order for this command to generate an entity type, the database table must have a primary key.
| Argument | Description |
|---|---|
| The connection string to the database. For ASP.NET Core 2.x projects, the value can be name= . In that case the name comes from the configuration sources that are set up for the project. | |
| Option | Description | |
|---|---|---|
| —data-annotations | Use attributes to configure the model (where possible). If this option is omitted, only the fluent API is used. | |
| -c | —context | The name of the DbContext class to generate. |
| —context-dir |
The following example scaffolds all schemas and tables and puts the new files in the Models folder.
The following example scaffolds only selected tables and creates the context in a separate folder with a specified name:
dotnet ef migrations add
Adds a new migration.
| Argument | Description |
|---|---|
| The name of the migration. |
| Option | Description |
|---|---|
| The directory (and sub-namespace) to use. Paths are relative to the project directory. Defaults to "Migrations". |
dotnet ef migrations list
Lists available migrations.
dotnet ef migrations remove
Removes the last migration (rolls back the code changes that were done for the migration).
| Option | Description |
|---|---|
| —force | Revert the migration (roll back the changes that were applied to the database). |
dotnet ef migrations script
Generates a SQL script from migrations.
| Argument | 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. |
| Option | Description | |
|---|---|---|
| —output | The file to write the script to. | |
| -i | —idempotent | Generate a script that can be used on a database at any migration. |
The following example creates a script for the InitialCreate migration:
The following example creates a script for all migrations after the InitialCreate migration.
В этом руководстве мы добавим некоторые классы для управления роликами в БД. Эти классы будут частью “Model” в MVC.
Для работы с этими классами мы будем использовать технологию доступа к данным .NET Framework, известную как Entity Framework Core. Entity Framework Core (EF Core) раскрывает парадигму разработки, которая называется Code First. Сперва вы пишете код, а таблицы БД создаются из этого кода. Code First позволяет создавать объекты модели из простых классов. (Они также известны как POCO классы, от “plain-old CLR objects”). Если вам требуется сначала создать БД, вы все равно можете следовать этому руководству, чтобы получить информацию по MVC и EF разработке.
Создание нового проекта с отдельными пользовательскими аккаунтами¶
В текущей версии инструментария ASP.NET Core MVC для Visual Studio скаффолдинг модели поддерживается только тогда, когда вы создаете новый проект с отдельными пользовательскими аккаунтами. Надеюсь, скоро это будет исправлено. А пока мы создаем новый проект с тем же самым именем. Из-за этого вам нужно разместить данный проект в новой директории.
На странице Visual Studio Start нажмите New Project.

Кроме того, для создания нового проекта вы можете использовать меню. Нажмите File > New > Project.

В диалоговом окне New Project:
- На левой панели нажмите Web
- На центральной панели нажмите ASP.NET Core Web Application (.NET Core)
- Измените местоположение, чтобы оно отличалось от местоположения предыдущего проекта (директория должна быть другой), иначе выскочит ошибка
- Назовите проект “MvcMovie” (Это важно, поскольку когда вы будете копировать код, пространство имен совпадет).
- Нажмите OK

Чтобы работал движок скаффолдинга, Authentication должна быть установлена на Individual User Accounts.
В диалоговом окне New ASP.NET Core Web Application — MvcMovie:
- нажмите Web Application
- нажмите кнопку Change Authentication и измените аутентификацию на Indiv />
Следуйте инструкциям в Изменение названия и меню в файле с версткой , чтобы вы могли нажать ссылку MvcMovie и вызвать контроллер Movie. В этом руководстве мы проведем скаффолдинг контроллера.
Добавление классов модели¶
В Solution Explorer кликните правой клавишей мышки по папке Models > Add > Class. Назовите класс Movie и добавьте следующие свойства:
Кроме нужных свойств БД требует поле ID для первичного ключа. Соберите проект. Если вы не соберете приложение, то дольше получите ошибку.
Скаффолдинг контроллера¶
В Solution Explorer кликните правой клавишей мышки по папке Controllers > Add > Controller.

В диалоговом окне Add Scaffold нажмите MVC Controller with views, using Entity Framework > Add.

В диалоговом окне Add Controller:
В Visual Studio движок скаффолдинга создает следующее:
- контроллер (Controllers/MoviesController.cs)
- файлы представлений Razor Create, Delete, Details, Edit и Index (Views/Movies)
Visual Studio автоматически создал методы действия CRUD (create, read, update и delete) и представления (автоматическое создание действий CRUD и представлений известно как скаффолдинг). Скоро у вас появится полностью функционирующее веб приложение, которое позволит вам создавать, считывать, редактировать и удалять записи по роликам.
Если вы запустите приложение и нажмете на ссылку Mvc Movie, то выскочат следующие ошибки:

Мы последуем этим инструкция, чтобы подготовить БД для нашего приложения.
Обновление базы дынных¶
Перед обновлением БД нужно остановить IIS Express.
Остановка IIS Express:¶
- Кликните правой клавишей мышки по иконке IIS Express в уведомлениях
- Нажмите Exit или Stop Site

- Как вариант, вы можете выйти или перезагрузить Visual Studio
- Откройте командную строку с директорией проекта (MvcMovie/src/MvcMovie). Следуйте данным инструкциям, чтобы быстро открыть папку в директории проекта.
- откройте файл в корневой директории проекта (для этого примера используйте Startup.cs.)
- кликните правой клавишей мышки по Startup.cs> Open Containing Folder.

- “Shift + плавая клавиша мышки” по папке >Open command window here

- Запустите cd .. , чтобы вернуться в директорию проекта
- В командной строке запустите следующие команды:
Если IIS-Express запущен, выскочит ошибка CS2012: Cannot open ‘MvcMovie/bin/Debug/netcoreapp1.0/MvcMovie.dll’ for writing – ‘The process cannot access the file ‘MvcMovie/bin/Debug/netcoreapp1.0/MvcMovie.dll’ because it is being used by another process.’
Команды dotnet ef¶
- dotnet (.NET Core) — это кроссплатформенная реализация .NET. См. здесь
- dotnet ef migrations add Initial запускает миграционные команды Entity Framework .NET Core CLI и саму начальную миграцию. Параметр “Initial” не обязателен для первой (начальной) БД миграции. При этой операции создается файл Data/Migrations/ _Initial.cs, содержащий миграционные команды для добавления таблицы Movie в БД
- dotnet ef database update обновляет БД с помощью миграции, которую мы только что создали
Тестирование приложения¶
Если ваш браузер не может соединиться с приложением, подождите, как IIS Express его загрузит. Иногда это занимает до 30 секунд, пока вы не получите ответ на запрос.
- Запустите приложение и нажмите на ссылку Mvc Movie
- Нажмите на ссылку Create New и создайте запись о ролике

Возможно, вы не сможете ввести десятичные точки или запятые в поле Price . В таком случае для поддержки валидации jQuery вам потребуется глобализовать приложение. См. Дополнительные ресурсы. А пока что вводите целые числа, например 10.
In some locales you’ll need to specify the date format. See the highlighted code below.
При нажатии Create форма отправляется на сервер, где информация о ролике сохраняется в БД. Далее вы перенаправитесь на URL /Movies , где в списке сможете увидеть новый ролик.

Добавьте еще несколько записей. Попробуйте поработать со ссылками Edit, Details и Delete.
Изучение сгенерированного кода¶
Откройте файл Controllers/MoviesController.cs и изучите сгенерированный метод Index . Часть контроллера с методом Index показана ниже:
Конструктор использует внедрение зависимостей , чтобы внедрить контекст БД в контроллер. БД контекст используется в каждом методе CRUD контроллера.
Запрос к контроллеру Movies возвращает все записи тыблицы Movies , а затем передает данные представлению Index .
Строго типизированные модели и ключевое слово @model¶
Ранее мы рассмотрели, как контроллер передает данные или объекты представлению, используя словарь ViewData . Словарь ViewData — это динамический объект, который предлагает удобный способ передачи информации представлению.
MVC также дает возможность передавать представлению строго типизированные объекты. Такой подход улучшает проверку кода во время компиляции и предлагает более богатые возможности IntelliSense в Visual Studio (VS). Механизм скаффолдинга в VS использовал такой подход с классом MoviesController и представлениями, когда создавал методы и представления.
Изучите сгенерированный метод Details в файле Controllers/MoviesController.cs:
Параметр id передается как роутовые данные, например http://localhost:1234/movies/details/1 устанавливает:
- контроллер на контроллер movies (первый URL сегмент)
- метод действия на details (второй URL сегмент)
- id на 1 (последний URL сегмент)
Также вы можете передать id со строкой запроса:
Если Movie найден, экземпляр модели Movie передается представлению Details :
Изучите контекст файла Views/Movies/Details.cshtml:
Включив выражение @model в файл представления сверху, вы можете указать тип объекта, который ожидает представление. Когда вы создали контроллер, Visual Studio автоматически включил следующее выражение @model сверху файла Details.cshtml:
Эта директива @model позволяет получить доступ к ролику, который контроллер передал представлению, используя строго типизированный объект Model . Например, в представлении Details.cshtml код передает каждое поле с роликами вспомогательным методам HTML DisplayNameFor и DisplayFor с помощью строго типизированного объекта Model . Методы Create и Edit , а также представления передают объект модели Movie .
Изучите представление Index.cshtml и метод Index в контроллере Movies. Обратите внимание, как создается объект List , когда вызывается метод View. Код передает этот список Movies из метода действия Index представлению:
Когда вы создали контроллер, Visual Studio автоматически включил следующее выражение @model в файл Index.cshtml сверху:
Директива @model позволяет получить доступ к списку роликов, которые контроллер передал представлению, используя строго типизированный объект Model . Например, в представлении Index.cshtml код проходит циклом по роликам с помощью foreach в строго типизированном объекте Model :
Поскольку объект Model является строго типизированным (как объект IEnumerable ), каждый элемент в цикле прописывается как Movie .

Теперь у вас есть БД и страницы для создания, редактирования, обновления и удаления данных.
There are many people that have asked this question before on SO. For the last 3 hours I have sequentially tried each solution, and I get the same No executable found matching command "dotnet-ef" each time. I’d like to understand how to run the command and have it actually execute.
But first a little background:
I am learning how to use ASP.Net Core 1.1 MVC and Entity Framework Core. It is a Microsoft tutorial that can be found here.
The completed tutorial can be downloaded from git, as instructed. Performing these steps I open the download project and follow the steps in the readme.md file in the project root folder. It states the following:
After downloading the project, create the database by entering dotnet ef database update at a command-line prompt
Which I attempted. I used visual studio developer command prompt (as admin) and first change directory to the project root, where the appsettings.json and *.csproj file are located. I then typed in the following:
C:UsersusernameDownloadsDocs-masteraspnetcoredataef-mvcintrosamplescu-final>dotnet ef database update
No executable found matching command "dotnet-ef"
According to the tutorial, this should "work" as-is.
What is strange to me is that if I run the following command I get output, which indicates to me that dotnet.exe is working.
I am using Windows 10 and Visual Studio 2017 CE Version 15.2. I have both the ASP.NET and web development and .Net Core cross-platform development workloads installed.
I am also using .Net Framework Version 4.6.01586.





