Add migration initialcreate ошибка

I have several class files. Now I am adding a new model class and tried to type add-migration InitialCreate but am getting the following error:

PM> add-migration InitialCreate
Exception calling "LoadFrom" with "1" argument(s): "Could not load file or assembly 'file:///C:UsersuserDocumentsVisual Studio 2013Pro
jectsDigitalHealthWebPrevpackagesEntityFramework.6.1.3toolsEntityFramework.PowerShell.Utility.dll' or one of its dependencies. Operati
on is not supported. (Exception from HRESULT: 0x80131515)"
At C:UsersuserDocumentsVisual Studio 2013ProjectsDigitalHealthWebPrevpackagesEntityFramework.6.1.3toolsEntityFramework.psm1:780 c
har:62
+     $utilityAssembly = [System.Reflection.Assembly]::LoadFrom <<<< ((Join-Path $ToolsPath EntityFramework.PowerShell.Utility.dll))
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

You cannot call a method on a null-valued expression.
At C:UsersuserDocumentsVisual Studio 2013ProjectsDigitalHealthWebPrevpackagesEntityFramework.6.1.3toolsEntityFramework.psm1:781 c
har:50
+     $dispatcher = $utilityAssembly.CreateInstance <<<< (
    + CategoryInfo          : InvalidOperation: (CreateInstance:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Exception calling "CreateInstanceFrom" with "8" argument(s): "Could not load file or assembly 'file:///C:UsersuserDocumentsVisual Studi
o 2013ProjectsDigitalHealthWebPrevpackagesEntityFramework.6.1.3toolsEntityFramework.PowerShell.dll' or one of its dependencies. Opera
tion is not supported. (Exception from HRESULT: 0x80131515)"
At C:UsersuserDocumentsVisual Studio 2013ProjectsDigitalHealthWebPrevpackagesEntityFramework.6.1.3toolsEntityFramework.psm1:809 c
har:31
+     $domain.CreateInstanceFrom <<<< (
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

PM>

Itchydon's user avatar

Itchydon

2,5626 gold badges19 silver badges33 bronze badges

asked May 9, 2015 at 12:15

noushad mohammed's user avatar

0

Using the Package Manager, you need to re-install Entity Framework:

Uninstall-Package EntityFramework -Force

Then install it for each project:

Install-Package EntityFramework

Then do not forget to restart the studio.

https://stackoverflow.com/a/14994432/1845408

Community's user avatar

answered May 9, 2015 at 14:33

renakre's user avatar

Used the command EntityFramework6add-migration {migration name} instead. Microsoft changed the name of the command.

answered Aug 13, 2020 at 10:43

Alexander Townsend's user avatar

1

Just restart the visual studio and clean the solution and rebuild it again.

answered Feb 8, 2020 at 12:04

Fahad's user avatar

FahadFahad

911 silver badge3 bronze badges

1

Make sure that VS in admin mode

answered Aug 14, 2018 at 15:44

Osama Yassein's user avatar

2

In my case, it was a different entity-framework version between main project and the project containing DbContext.
I just updated version of package in both projects to v6.4.4

answered Aug 15, 2020 at 12:43

Yahya Hussein's user avatar

Yahya HusseinYahya Hussein

8,70715 gold badges57 silver badges112 bronze badges

1

I had a slightly different case today, I’m wirting the details here in case that might help somebody. The error was referencing one of my assemblies instead, on which the assembly containing the EF DbContext was depending.
I solved it setting the referenced assembly to «Copy Local» «true» so it’d make a local copy when building for migrations and therefore be able to find it.

answered Sep 29, 2016 at 19:14

baywet's user avatar

baywetbaywet

4,3424 gold badges19 silver badges48 bronze badges

you need to re-install Entity Framework:

answered Jun 30, 2017 at 9:33

Anusha B's user avatar

Anusha BAnusha B

911 silver badge10 bronze badges

I went to «Manage Nuget Packages for Solution…» and updated all my packages. This worked for me.

Then I got another error Cannot bind argument to parameter 'Path' because it is null.

Setting another project as startup project other then my web app, before running any EF command in Package Manager Console, worked for me.

answered Nov 3, 2019 at 13:23

Mari Faleiros's user avatar

1

Whats missing are the dlls from (Solution Folder)/packages/EntityFramework.6.1.3/tools/.

Things I would try:

  1. Nuget will keep a copy of the .nupkg you might find the missing files there ((Solution Folder)/packages/EntityFramework.X.Y.Z/) (Open the nupkg as zip)
  2. If not you may have luck redownloading the package manually here https://www.nuget.org/packages/EntityFramework (Make sure you download the right packages. In your case it would be 6.1.3)

If that doesnt work you can retry one of the above solutions of completely removing and reinstalling EF but make sure you install the same version for each project.

Also there seem to be versions that dont include those files. For example as of writing this answer 6.3.0 actually doesnt include the dlls needed while 6.1.3 does. I also had success copying the dlls from an older version like 6.1.3 into the newer like 6.3.1 (Might give a warning but generally works as expected).

answered Oct 10, 2019 at 19:08

Lukas Willin's user avatar

I’ve migrated from .NET Core 1.1 to .NET Core 2.0. Have some troubles with EF Core 2.0. I’m using multi environment. dotnet-ef command missing -e (environment) option, that is required in my project.

dotnet ef migrations add Test -c BackendContext -v

Error

Using project Backend.csproj'.
Using startup project Backend.csproj'.
Writing 'objBackend.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:UsersuserAppDataLocalTemptmpE244.tmp /verbosity:quiet /nologo Backend.csproj
Writing 'objBackend.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:UsersuserAppDataLocalTemptmpE468.tmp /verbosity:quiet /nologo Backend.csproj
dotnet build Backend.csproj /verbosity:quiet /nologo

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.33
dotnet exec --depsfile binDebugnetcoreapp2.0Backend.deps.json --additionalprobingpath C:Usersuser.nugetpackages --additionalprobingpath "C:Program FilesdotnetsdkNuGetFallbackFolder" --runtimeconfig binDebugnetcoreapp2.0Backend.runtimeconfig.json C:Usersuser.nugetpackagesmicrosoft.entityframeworkcore.tools.dotnet2.0.0toolsnetcoreapp2.0ef.dll migrations add Test -c BackendContext --assembly binDebugnetcoreapp2.0Backend.dll --startup-assembly binDebugnetcoreapp2.0Backend.dll --project-dir  --verbose --root-namespace Backend
Using assembly 'Backend'.
Using startup assembly 'Backend'.
Using application base binDebugnetcoreapp2.0'.
Using working directory ''.
Using root namespace 'Backend'.
Using project directory ''.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding BuildWebHost method...
No BuildWebHost method was found on type 'Backend.Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'BackendContext'.
Found DbContext 'LiteContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'BackendContext'. Add an implementation of 'IDesignTimeDbContextFactory<BackendContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time. ---> System.MissingMethodException: No parameterless constructor defined for this object.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Activator.CreateInstance(Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass12_3.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'BackendContext'. Add an implementation of 'IDesignTimeDbContextFactory<BackendContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

BackendContext

public class BackendContext : DbContext
{
     public BackendContext(DbContextOptions<BackendContext> options)
         : base(options)
     { }
}

In Startup.cs

services.AddDbContext<BackendContext>(opts =>
                opts.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

EF Core version: 2.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: win10-x64
IDE: Visual Studio 2017
.NET Core SDK info:

.NET Command Line Tools (2.0.0)

Product Information:
 Version:            2.0.0
 Commit SHA-1 hash:  cdcd1928c9

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.15063
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:Program Filesdotnetsdk2.0.0


Microsoft .NET Core Shared Framework Host



  Version  : 2.0.0

  Build    : e8b8861ac7faf042c87a5c2f9f2d04c98b69f28d

RRS feed

  • Remove From My Forums
  • Question

  • User887623398 posted

    Hi

    I run this command on package manager console :

    pm>add-migration FirstAppDemo

    but keeping <g class=»gr_ gr_100 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace» id=»100″ data-gr-id=»100″>get</g> this image:

    The project first app demo failed to build.

    What should I do?

    please inform.

    regards

    Saeed

All replies

  • User887623398 posted

    Thanks for your reply.

    I’m afraid my entity framework and sql configuration is correct in start up.cs.

    Here comes my configuration:

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
                
                var sqlconnection = "Data Source=(localdb)\mssqllocaldb;Initial Catalog=FirstAppDemo";
                services.AddDbContext<FirstAppDemoDbContext>(dbcontextoption => dbcontextoption.UseSqlServer(sqlconnection));
    
    
    
            }

    Would you please let me know if any thing is wrong?

  • User-369506445 posted

    It’s not depended to your config

    According to your error, I said first build your project and sure you do not get any error

    If your project become build success

    Then 

    • Run the Enable-Migrations command in Package Manager Console . (make sure that default project is the project where your context class is)

    Next Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was
    created

  • User887623398 posted

    I built my project and there is no error.

    In <g class=»gr_ gr_20 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace» id=»20″ data-gr-id=»20″>microsoft</g> documentation comes to this command:

    Add-Migration InitialCreate

    and when I write and run this command after a while this error comes which is highlighted:

    Object reference not set to an instance of an object.

    please inform.
     

  • User1528429020 posted

    Having the same problem, if you found any solution please help

    PM> add-migration AddBooleanPurposeColumnsToCustomersTable
    The project ‘CustomersDemo’ failed to build.

Problem

Here is the basic setup of this problem:

  1. You created a .Net Core application and wanted to use .Net Core EF in your application for the data layer.
  2. You have already installed .Net Core EF from NuGet
  3. You setup your data layer using Fluent API
  4. You are ready for adding your initial migration, but using the .Net CLI keeps giving you a bogus error like the one shown below after running the following command:

dotnet ef migrations add InitialCreate

C:DevYourProject.Data>dotnet ef migrations add InitialCreate
The specified framework version '2.1' could not be parsed
The specified framework 'Microsoft.NETCore.App', version '2.1' was not found.
  - Check application dependencies and target a framework version installed at:
      C:Program Filesdotnet
  - Installing .NET Core prerequisites might help resolve this problem:
      http://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
  - The .NET Core framework and SDK can be installed from:
      https://aka.ms/dotnet-download
  - The following versions are installed:
      2.0.3 at [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
      2.0.5 at [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
      2.0.7 at [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
      2.0.9 at [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
      2.1.3-servicing-26724-03 at [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
      2.1.4 at [C:Program FilesdotnetsharedMicrosoft.NETCore.App]
      2.1.5 at [C:Program FilesdotnetsharedMicrosoft.NETCore.App]

Gotcha

From what I have seen there are a few steps to remedy this problem and it isn’t obvious if you are new to .Net Core at all. I got most of my information by cross referencing articles and blog posts, but this one explains it well: https://github.com/dotnet/core/issues/1843

How to fix the stupid problem

Add the XML that is between the “PropertyGroup” tags to your project file that is referencing the Entity Framework NuGet package.

<PropertyGroup>
  <GenerateRuntimeConfigurationFiles>True</GenerateRuntimeConfigurationFiles>
</PropertyGroup>

If at this point you were to run the “dotnet ef migrations add InitialCreate” command again you would get the following error:

C:DevYourProject.Data>dotnet ef migrations add InitialCreate
Your startup project 'SimpleSmtpInterceptor.Data' doesn't reference Microsoft.EntityFrameworkCore.Design. 
This package is required for the Entity Framework Core Tools to work. Ensure your startup project is 
correct, install the package, and try again.

That being said the next step according to the error is to add the missing NuGet package “Microsoft.EntityFrameworkCore.Design” to your project.

At this point when you run the “dotnet ef migrations add InitialCreate” command again you could run into more issues, but it is all first time setup of your context class. I could keep listing possibilities, but this would be a never ending article at that point, most of which is covered by google.

.Net EF Core migrations instructions

My rant you can ignore

It’s obvious .Net Core is still under developed to be having problems like this. Microsoft needs to hurry the hell up and get things up to par to .Net Framework; I feel like it’s been long enough at this point. I am never one to jump on the bandwagon early just so I can say I am doing something, especially not at the cost of inconvenience spent as time debugging their mistakes.

In this article, we are going to learn how to solve the Command or File Was Not Found EF Core migration error.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Before we start, we want to mention that we are not going to talk about how to create migrations in EF Core. We assume you are already familiar with that. Of course, to learn more about EF Core Migrations, you can check out our article: Migrations and Seed Data with Entity Framework Core.

Now, let’s continue.

Let’s imagine we have a Customer.cs class and we intend to create a database with a Customer table:

public class Customer
{
    public Guid Id { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public int Age { get; set; }
    public string? Address { get; set; }
    public string? CardNumber { get; set; }
}

Then, if we try to run EF Core migrations using dotnet ef migrations add InitialCreate , we are going to get an error:

Could not execute because the specified command or file was not found.
Possible reasons for this include:
* You misspelled a built-in dotnet command.
* You intended to execute a .NET program, but dotnet-ef does not exist.
* You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.

From this error, we understand that we have an issue related to our command and we also see several reasons that can cause it:

The first one – You misspelled a built-in dotnet command is basically not true because we use the command from Microsoft’s official documentation.

Let’s check the second one – You intended to execute a .NET Core program, but dotnet-ef does not exist.  This can lead us to our solution for the issue since we are obviously missing something.

Let’s continue inspecting the last one, which mentions the global tool and a not found path.  It should help us as well since we use a dotnet ef command and it is not recognized on our machine, so it is somehow similar to the second reason.

So, for sure, we are missing something. But what is it, and how to fix it?

How to Fix the Command or File Was Not Found Error?

If we inspect this announcement for Entity Framework Core 3.0 Preview 4, we can find that the dotnet ef tool is no longer part of the .NET Core SDK. That’s why in our example, we can’t execute the migration.

That said, we should install the dotnet ef tool on our machine:

dotnet tool install --global dotnet-ef

Now we should be able to run our dotnet ef commands successfully.

Let’s execute our migration command again:

dotnet ef migrations add InitialCreate

And now we get a successful result:

Build started ...
Build succeeded.
Done. To undo this action, use 'ef migrations remove'

Then, to apply our changes to the database, we have to execute a new command:

dotnet ef database update

And if we inspect the message:

Build started ...
Build succeeded.
Applying migration '20220401210459_InitialCreate'.
Done.

We can see that we’ve applied our migration successfully.

Conclusion

In this article, we have explained the reasons behind “Dotnet EF Not Found Error” and learned how to fix it with our example.

Понравилась статья? Поделить с друзьями:
  • Adblock выдает ошибку
  • Adb ошибка при запуске приложения 0xc000007b
  • Adb ошибка no devices emulators found
  • Adb ошибка 10061
  • Adb ошибка 10060