dotnet ef не удалось выполнить так как не найдены указанная команда или указанный файл
No executable found matching command «dotnet-ef»
I’m doing a project sample by using ASP.Net Core RC2 with Microsoft.EntityFramework.Core and SQLite.
But, when I run this command :
Here is my project.json configuration:
13 Answers 13
Entity Framework Core 1.0
You should just need to update the tools section of your project.json file to include this:
This should make the dotnet ef commands available.
Important
I should also note here that the dotnet ef commands will only be available when running them from the same directory which contains the project.json file.
Entity Framework Core 1.1
Specific to VS2017 15.3 or greater and ASP.NET CORE 2.0 or later.
Install nuget for db provider via command line or nuget package manager.
Install design time tools via commandline or nuget manager in VS2017.
This enables dotnet ef * at the command line in the project directory.
Enables dotnet ef * commands at the command line in the project directory,
To fix that, you need to:
If you already have a tools json key or an element with one or more existing DotNetCliToolReference elements, just add the new ones to the existing group.
IMPORTANT: other than performing the above steps, you have to launch the dotnet ef command within the project root folder (the one containing the project file), otherwise it won’t work.
For additional info and an extensive explanation of the issue you can read more on my blog post.
Cannot find command ‘dotnet ef’
cannot find command dotnet ef
I’ve just about looked everywhere and none of the suggestions worked.
The result of running ‘dotnet ef’:
12 Answers 12
This was the result of the above install command:
How to fix this
For Linux and macOS, add a line to your shell’s configuration:
When you start a new shell/terminal (or the next time you log in) dotnet ef should work.
For Windows:
See this question on how to add to the PATH environment variable.
What’s going on?
The second and the third one both refer to dotnet trying to find a dotnet-ef command but can’t find it. As the third point says, dotnet-ef is not in your path.
Global Tools can be installed in the default directory or in a specific location. The default directories are:
But also note this part from docs:
These locations are added to the user’s path when the SDK is first run, so Global Tools installed there can be called directly.
So, it sounds like something went wrong. If you installed using a manual tarball, the SDK screwed up and you should report this bug to Microsoft. If you use a distribution package, they screwed up and you should report this as a bug to them.
При использовании Visual Studio рассмотрите возможность использования средств консоли диспетчера пакетов вместо средств CLI. Средства консоли диспетчера пакетов автоматически:
Установка инструментов
dotnet ef можно установить в качестве глобального или локального средства. Большинство разработчиков предпочитают устанавливать средство dotnet ef в качестве глобального средства, используя следующую команду:
Чтобы использовать его в качестве локального средства, восстановите зависимости проекта, в котором оно объявляется в качестве соответствующей зависимости, с помощью файла манифеста средства.
Обновите средство с помощью следующей команды:
Прежде чем можно будет использовать средства в конкретном проекте, необходимо добавить в Microsoft.EntityFrameworkCore.Design него пакет.
Проверка установки
Выполните следующие команды, чтобы убедиться, что средства EF Core CLI установлены правильно:
Выходные данные команды определяют версию используемых средств:
Обновление средств
Использование средств
Перед использованием этих средств может потребоваться создать запускаемый проект или задать среду.
Целевой проект и запускаемый проект
Команды ссылаются на проект и запускаемый проект.
Запускаемый проект — это тот, который выполняет сборка и запуск средств. Средства должны выполнять код приложения во время разработки для получения сведений о проекте, таких как строка подключения к базе данных и Конфигурация модели. По умолчанию проект в текущем каталоге является запускаемым проектом. Можно указать другой проект в качестве запускаемого проекта с помощью параметра.
Запускаемый проект и целевой проект часто являются одним и тем же проектом. Типичный сценарий, в котором они являются отдельными проектами, состоит в следующих случаях:
Другие целевые платформы
Среда ASP.NET Core
Чтобы указать среду для проектов ASP.NET Core, задайте переменную среды ASPNETCORE_ENVIRONMENT перед выполнением команд.
Начиная с EF Core 5,0, дополнительные аргументы также могут передаваться в Program. Креатехостбуилдер, что позволяет указать среду в командной строке:
— Токен направляет dotnet ef все, что следует за аргументом, и не пытается проанализировать их как параметры. Все дополнительные аргументы, не используемые, dotnet ef пересылаются в приложение.
Общие параметры
Параметр | Short | Описание |
---|---|---|
—json | Отображение выходных данных JSON. | |
—context | Класс DbContext для использования. Только имя класса или полный квалификатор с пространствами имен. Если этот параметр не указан, EF Core найдет контекстный класс. Если существует несколько классов контекста, этот параметр является обязательным. | |
—project |
Начиная с EF Core 5,0, в приложение передаются дополнительные аргументы.
dotnet ef database drop
Удаляет базу данных.
Параметр | Short | Описание |
---|---|---|
—force | Не подтверждайте. | |
Показывает, какую базу данных следует удалить, но не удалять. |
dotnet ef database update
Обновляет базу данных до последней миграции или до указанной миграции.
Аргумент | Описание |
---|---|
Целевая миграция. Миграция может быть идентифицирована по имени или по ИДЕНТИФИКАТОРу. Число 0 — это особый случай, который означает перед первой миграцией и приводит к отмене всех миграций. Если миграция не указана, команда по умолчанию принимает значение последней миграции. |
В следующих примерах база данных обновляется до указанной миграции. В первом случае используется имя миграции, а во втором используется идентификатор миграции и указанное соединение:
dotnet ef dbcontext info
Возвращает сведения о DbContext типе.
dotnet ef dbcontext list
Перечисляет доступные DbContext типы.
dotnet ef dbcontext scaffold
Создает код для DbContext типов сущностей и для базы данных. Чтобы эта команда создавала тип сущности, таблица базы данных должна иметь первичный ключ.
Параметр | Short | Описание | ||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
—data-annotations | Используйте атрибуты для настройки модели (по возможности). Если этот параметр пропущен, используется только API-интерфейс Fluent. | |||||||||||||||||||||||||||||||||||
—context | -c | Имя DbContext создаваемого класса. | ||||||||||||||||||||||||||||||||||
—context-dir Следующий пример формирует только выбранные таблицы и создает контекст в отдельной папке с указанным именем и пространством имен: В следующем примере считывается строка подключения из набора конфигурации проекта с помощью средства диспетчера секретов. В следующем примере пропускается формирование шаблонов OnConfiguring метода. Это может быть полезно, если требуется настроить DbContext за пределами класса. Например, ASP.NET Core приложения обычно настраивают его в Startup.ConfigУресервицес. Добавлено в EF Core 5,0. dotnet ef dbcontext scriptСоздает скрипт SQL из DbContext. Обход всех миграций. Добавлено в EF Core 3,0.
dotnet ef migrations addДобавляет новый перенос.
dotnet ef migrations listСписок доступных миграций.
dotnet ef migrations removeУдаляет последнюю миграцию с откатом изменений кода, выполненных для последней миграции.
dotnet ef migrations scriptСоздает скрипт SQL из миграции.
В следующем примере создается скрипт для миграции InitialCreate: В следующем примере создается скрипт для всех миграций после миграции InitialCreate. Commentsnatemcmaster commented Apr 22, 2019Filing on behalf of @DamianEdwards Describe what is not working as expected. Steps to reproduceThe text was updated successfully, but these errors were encountered: shawty commented Apr 23, 2019Just hit by exactly the same scenario here: After installing the tools using the same command line. Just to make sure my tooling was working in the latest V3 sdk preview natemcmaster commented Apr 23, 2019shawty commented Apr 23, 2019I’m was under the impression it was something to do with the builds still being in preview, so I assume this will just automatically fix itself once DNC3 goes prod. ajcvickers commented Apr 24, 2019The behavior on 3.0 is expected because install doesn’t look at preview packages, and hence tries to load the 2.2 package, which is not intended to be loaded in this way. This means that: We will discuss this in triage, but for now this feels like a won’t fix to me. shawty commented Apr 24, 2019I agree to be fair. I don’t expect a fix per say, but what might be an idea is to borrow from the NuGet screen in VS, where there is a tick box that says «consider previews», and implement something like that, either via a command line option, or an environment variable. The only reason I suggest this, is because folks like me don’t always/or are not always privy to the actual versions we need for a given core tooling version. In my case above, I defaulted to the * in my install simply because I didn’t expect any different, once it was pointed out I needed a specific version, and the version was given it was obvious, and the penny dropped. There are however many developers now converting to use Core, that don’t have the benefit of experience, and so will blindly type in any command line version combo there told too, thus making more work for the support teams when things inevitably go wrong for them. Having a «tick» that can be enabled (Disabled by default) that allows the command to stop, look at it’s actual version and see if there is a preview that matches it, would them mean support is as easy as Just my thoughts on things, not really expecting any note to be taken of them 🙂 AhmedHemdan21 commented May 9, 2019 •when i try to execute
then i did run the command again then i got this error
and when i have checked this path i found that it installs it as so i had to rename the folders manually to match and it worked fine ajcvickers commented May 9, 2019@AhmedHemdan21 The more appropriate workaround is to install with a preview version specified, as shown above and in the announcement. shawty commented May 9, 2019I concur with @ajcvickers renaming and/or messing about with the paths, folders and installed commands can never be a good thing, using the version suffix above is the safest way of ensuring you don’t break anything even accidentally. BrettBaggott commented Jun 4, 2019I’m sure anyone reading through all this would understand this but what you really should do is head to Nuget and use the latest version (assuming you’ve just installed the latest 3.0 preview SDK), which for me, getting here after installing preview5 was not what is referenced, of course. I went here and checked: and used preview5 instead. Just worth being explicit just in case 😉 bill-barron commented Jun 13, 2019mzrks commented Jul 3, 2019 •Where I can find a list with all versions of dotnet tools? shawty commented Jul 3, 2019There’s not an «Official one» that I know of, but the tools usually follow the version on the runtime lib your trying to use, so Gives you the NuGet page (and thusly the version) for preview 5, and if you scroll down you’ll see the versions for the other previews too. Copying those versions should (In theory) work. bricelam commented Jul 3, 2019shawty commented Jul 3, 2019Cheers Brice, I knew you’d have the answer 🙂 mzrks commented Jul 3, 2019
Gives you the NuGet page (and thusly the version) for preview 5, and if you scroll down you’ll see the versions for the other previews too. Copying those versions should (In theory) work. Thank you, it really works. prakash-manit commented Jul 17, 2019antonioortizpola commented Jul 17, 2019@prakash-manit I would strongly suggest to install the right version to avoid the issues as @shawty suggest. From my experience and what I am seeing in the post, the best solution for this problem is to check your highest net core version and install that EF version as @BrettBaggott suggest vscodewinodws commented Aug 19, 2019evan-boissonnot commented Sep 2, 2019acbaile5 commented Oct 31, 2019 •
so i had to rename the folders manually to match and it worked fine I have the same problem. Did you rename the folders? Not some configuration files? Is it safe? I see version of dotnet-ef.dll matches. EmKayUltra commented Nov 17, 2019 •Had the same problem (Windows machine): First question: Why is this happening? Is it because dotnet ef is no longer part of the default SDK as of 3.0? Shouldn’t they live in isolation from each other? shawty commented Nov 17, 2019@EmKayUltra I’m not in any way speaking on behalf of Microsoft or the Entity framework team here, but this is NO LONGER an issue. When I first opened this issue, I was unaware of how the versioning for the preview versions of dotnet core worked with regards to loadable tools. Since then, I’ve done my research and spoken to many members of various MS development teams who have confirmed that tool versions are always set to match dotnet core versions. This has nothing to do with MS separating out the tools, but it has everything to do with them enforcing matching versions so that you get the correct tool for the version of dotnet you are using. If you then install dotnet core 3.0 without uninstalling anything else, your default working version of dotnet core will be set to version 3.0 At this point, dotnet-ef will cease to work, and the reason for this is because you at that point will not have a v3.0 compatible version of the tool installed. The same is also true for any templates you have installed. I’ve actually created a small batch file with all my statements in, and I run it every time I update my dotnet core SDK version, thus ensuring that I have the latest versions of anything I have added to the install. You will ONLY get problems installing these tools, in 2 specific scenarios: The MS team (If you read above) have closed this issue way back in October, as there’s nothing to answer here, there is no issue, no fault, no bug or anything. The only reason I know this keeps getting hits is because as the original author GitHub notifies me every time there is a change on it. So finally I ask only this: If after reading it all, you still believe that you’ve encountered a bug, then open a new issue in the issue tracker, and reference this thread. Adding your «i have a bug» post to this thread is NOT going to get you the answer or the assistance you seek, because it’s now a closed issue. Не удается найти команду ‘dotnet ef’?Результат выполнения ‘dotnet ef’ 9 ответовЯ уже некоторое время использую VS для Mac с EF Core 2.2, и все идет хорошо. Сегодня я обновил VS для Mac, так как он действительно устарел, и после обновления я больше не могу запускать команду dotnet ef : Не удалось выполнить, так как указанная команда или файл не были найдены. Возможные причины. Это было результатом приведенной выше команды установки: Как это исправитьДля Linux и macOS добавьте строку в конфигурацию вашего shell: When you start a new shell/terminal (or the next time you log in) dotnet ef should work. For Windows: See this question on how to add to the PATH environment variable. What’s going on?The second and the third one both refer to dotnet trying to find a dotnet-ef command but can’t find it. As the third point says, dotnet-ef is not in your path.
Но также обратите внимание на эту часть из документов:
Так что, похоже, что-то пошло не так. Если вы установили его с помощью ручного тарбола, то SDK облажался, и вы должны сообщить об этой ошибке в Microsoft. Если вы используете дистрибутив, они облажались, и вы должны сообщить им об этом как об ошибке. Я перепробовал все ответы выше и не работал на своем mac с последним обновлением Catalina. Что касается исправления пути: Имейте в виду, что это добавляет путь к переменной окружения User PATH, а не System PATH. При запуске «Developer Command Prompt» или «Developer Powershell» из Visual Studio он не использует переменную пользовательского пути. Вам также нужно будет добавить его в системную переменную окружения. Кроме того, вам нужно будет перезапустить VS, прежде чем изменение вступит в силу.
Если вышеприведенная команда дает вам ошибку, пожалуйста, выполните следующие действия.
1-Вам нужно добавить %USERPROFILE%.dotnet\tools к PATH. 2-If не существует, затем выполните эту команду инструмент для установки dotnet ограничителя-г dotnet ограничителя-эф Похожие вопросы:Есть много людей, которые задавали этот вопрос раньше на SO. В течение последних 3 часов я последовательно пробовал каждое решение, и каждый раз получал одно и то же No executable found matching. Я уже некоторое время использую VS для Mac с EF Core 2.2, и все идет хорошо. Сегодня я обновил VS для Mac, так как он действительно устарел, и после обновления я больше не могу запускать команду. Я пытаюсь разработать некоторые web APIs с помощью dotnet core 3 preview 4. Я знаком с ядром dotnet и его библиотеками, такими как EF core, Identity и т. д. Но теперь с версией 3 preview 4.
|