Entity Framework Migrations does not find my DbContext - entity-framework

I have looked around stackoverflow and search the internet but did not find a answer.
If i try to Enable-Migrations for my project i get the Exception
Error while searching for context type (specify -Verbose to see exception details).
Edit the generated Configuration class to specify the context to enable migrations for.
So my question is:
What are the requirements for my project / DbContext in order to let the Entity Framework Migrations find my DbContext WITHOUT specifying it manually ?
Thanks in advance!

You project will need a database class which derive from DbContext, and in your web.config/app.config, you will need a connection string which points to the right database which is used by your database class.
The project you run the command on will need a configuration file to have the right connection string. Even it's class library, you still need this configuration.

I have had a similar issue which was related to the wrong version of Entity Framework being referenced.
You can try executing Update-Package EntityFramework from the Package Manager Console in Visual Studio.
If that does not help then just manually reference the EF 4.3 library from your project and then re-run the Enable-Migrations -force for your project(s).
Cheers.

Related

Error when adding migration to EntityFramework project

Working on a .NETCore MVC back end that's using EntityFramework.
The Solution as a Service project, EntityFramework project, and an API (MVC) project. The API project is the envy point/startup.
It's an existing project, and there was an initial migration file which I used to setup the database from the command line using: dotnet ef database update.
Now, I've added a new model to the EntityFramework project, and added the appropriate public DbSet to the Context class. Now I'm trying to generate the update migration file for it so I can update the database.
Using dotnet ef migrations add migration_002 gave an error of:
Unable to create an object of type 'StartNetContext'. Add an
implementation of 'IDesignTimeDbContextFactory' to
the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
additional patterns supported at design time.
Searching for that turned up posts and blogs related to upgrades from EF 1 -> 2 ... not appropriate in this case. Or pointing to issues when creating the initial migration when there's also seeding happening... again, also not appropriate in this case. When I add the -v option, I get a bit more info:
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to
create an object of type 'StartNetContext'. Add an implementation of
'IDesignTimeDbContextFactory' 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.
Ugh. What? Why do I need that? Searching that points to re-arranging how the startup is configured... specifically making sure that the. AddDbContext is being called - which it is...
I feel like I'm going in circles... it should work... someone created the initial migration, so it had to have worked, right?
NOTE: I'm on a Mac, so there's no using the Package Manager console, so selecting target projects, etc isn't a solution either. This all needs to be done right from the CLI.
Add the following class in your main project.
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
public YourDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
DbContextOptionsBuilder<YourDbContext> builder = new DbContextOptionsBuilder<YourDbContext>();
string connectionString = configuration.GetConnectionString("YourDbContextConnectionName");
builder.UseSqlServer(connectionString);
return new YourDbContext(builder.Options);
}
}
Hope your error will go away!
So it turns out in my case it was a simple flag on the CLI... Despite having the web api project marked as the startup project in the solution, I needed to specify it on the command line as well.
dotnet ef migrations add migration_002 -s ../MyWebApp.Api
I got that from this post.
Adding the -s flag worked, even without the code and adding the class (which I did try first, but ran into problems with the return statement).
It's the simple things in life.

How can I run an Entity Framework 7 migration on a remote database using Powershell?

In a standalone entity framework 7 project (note, not a MVC project with an entity context where the command DNX might be used), how can I run a migration on a remote database using Powershell?
I am currently using Entity Framework 7.0.0-rc1-final with Visual Studio 2015 (14.0.23107.0).
At the moment there is no way you can use pure PowerShell to do this because a utility like migrate.exe does not exist yet and importing the EF PS modules is not possible as they require a Package Manager PowerShell Host.
Here are some ideas how you can update a remote db in EF7:
One thing you could do is use the package manager console commands from within VS as usual to update the remote db. You can create a second context that has the remote db connection string and use the update-database command specifying the context to use. These commands require the following package in EF7:
https://www.nuget.org/packages/EntityFramework.Commands/.
I have done this successfully in a class lib project.
Another solution would be to use DNX commands by creating a DNX project instead of a classic one. DNX projects are not just for web sites, it is just another type of project. Here is a link that shows how to create a console app DNX project:
http://docs.asp.net/en/latest/dnx/console.html.
So with this type of project you can use the provided DNX commands that you seem to be aware of.
I hope this helped. Maybe we can give more help if you describe your situation and your end goal in more detail.
Answer too long as a comment, so adding it here...
Have you looked at this article and the links in the answer?
From that answer
The problem with importing the module into a PowerShell console is that I believe the module expects to run in a context where it has a Visual Studio DTE object available. That environment is the NuGet Package Manager Console. This issue has been brought up before. Check out this blog post and this SO question.
This blog post shows how to write code that does migrations.
What might be helpful for readers of this question is what you have tried, what is not working, and other information that might help solve your problem.

Ef Migration Code Based

I'm starting to turn migration manuals in my solution.
But I have a problem, it is several days that I could not understand.
My solution is divided into several projects, a project for the view (Sedna.UI) a project for the db where are my entity and my contexts. (Sedna.Domain).
I have 3 contexts, 2 have automatic migrations while the main one I would turn migration manual (SednaContext)
Nuget package manager console there is a dropdown and I select the Default project "Sedna.Domain" then when i run Enable-Migrations -ContextTypeName Sedna.Domain.UnitOfWork.SednaContext ... I get an error: "No migrations configuration type 'Sedna .Domain.Migrations.Configuration 'was found in the assembly "Sedna.Domain" "while I find him in the project.
I'm going crazy I do not understand why?
Screencast
Try specifying the ContextProjectName as well. http://bartwullems.blogspot.com/2014/05/entity-framework-migrations-no-context.html Also see Enable Migrations with Context in Separate Assembly?

Code First Migrations for a custom NuGet package can't be executed from main application

I have created a module to be included in a main MVC3 web application. The module is packaged into a NuGet package and it can be installed and uninstalled via NuGet. Both, the main site and the module use Code First, EF >= 4.3
To create the package I have another MVC3 site and all the functionality is inside an area, so to create the package I just pack the libraries, the views and all the needed files. Database Migrations work fine in the project and the package is created nicely.
Now I install the package in the main site via NuGet. This site is in another solution, and the solution has two projects:
MyProject.Web.UI: this is an Mvc3 project
MyProject.EntityFramework: this is a class library with all the models, dbContext for MyProject...
The package is installed correctly and the Area, the Area views and libraries are correctly installed.
The problem now is how I update the database? I've tried first to run "Update-Database" but I get the message:
"No migrations configuration type was found in the assembly
'MyProject.Web.UI'. (In Visual Studio you can use the
Enable-Migrations command from Package Manager Console to add a
migrations configuration)."
I've tried then to enable the migrations with "Enable-Migrations" but I got this other message:
"No context type was found in the assembly 'MyProject.Web.UI'."
I tried also just to run the site and see if the changes are automatically applied but I get the exception page with the typical message:
"The model backing the 'NugetPackageDbContext' context has changed
since the database was created. Consider using Code First Migrations
to update the database"
I don't know what to do to update the database with the required changes in migrations that come in the NuGet package. Any one could put some light here in this matter? I'm quite new to Migrations, maybe there are some configs to update the database if there is a change instead of running the commands in the console, I'm a bit lost.
Thanks in advance :)
Good news! It seems that I got it. I was looking for a way to make the NuGet package to update the database to the latest version.
Well, this package comes with an Admin controller, so I added a new action called Update:
public ActionResult Update()
{
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<MyPackageDbContext, MyPackage.Migrations.Configuration>());
return View();
}
In my Configuration class for the migrations I have:
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
I have to say that in my way to do all of this I've found a few strange behaviors. One thing that surprises me is this, I don't know if this is normal, read the secuence:
Package installed with new migrations but database not up to date. So if I access the EF this affected by this I get the exception about this. Ok up to this.
I go to my action /MyPackage/Admin/Update and run it. Apparently it runs. I go to the database and I don't see changes. Even the migrations table does not have a new row.
I access again the EF part that displayed the exception before (point number 1) and then everything goes through, database is updated and the migrations table shows the new line.
One thing that you have to notice is that the Configuration class is internal, but because this is a module I needed to be accessible from another assembly. I tried to make it public but I got some strange warnings/errors that I don't know if they are related. So in the end I kept it internal but used
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OtherAssembly")]
I've found a few of strange behaviors in Visual Studio with all this stuff of the NuGet packages, CF, migrations ... I don't know if these things are bugs, but all this thing took me two full working days.
I hope it is useful for any other that wants to create a CF NuGet package that is updateable.
In package manager console you will need to the Default project to MyProject.EntityFramework
You may also need to make sure MyProject.Web.UI is set as the start up project (in case there are multiple), then you can pass in the connection string into update command:
Update-Database -ConnectionStringName MyConnStringName
This should update the database correctly, unless there is data that will be lost.
If your DbContext is in MyProject.EntityFramework then the Default Project in the Package Manager Console needs to be set to MyProject.EntityFramework before you can use Update-Database.
I realize that this question is very old, but since I don't see this answer I'll throw it in anyway.
To perform migrations and such on projects or external references you can still use the same three command:
Enable-Migrations
Add-Migration
Update-Database
but you wil need to supply some additional parameters. For the Enable-Migrations command you will need to add the -ContextTypeName and optionally the -ContextAssemblyName commands like so:
Enable-Migrations -ContextTypeName MyProject.EntityFramework.NugetPackageDbContext -ContextAssemblyName MyProject
This will give you a migration configuration class in your current project. The other two commands will require you to specify this configuration class:
Update-Database -ConfigurationTypeName MyProject.Web.UI.Migrations.Configuration
Hope that helps

Add-Migration throws error with no configuration found

When I try to create a new migration using EF Code-First the package manager console gives me an error saying: 'No migrations configuration type was found in the assembly 'Project.DataAccess'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).'
I've previously used this method on THIS project successfully and the project do have a Configuration file with all the correct inheritance.
I also tried specifying all the parameters -Name, -StartupProjectName etc. but no change. When trying to re-enable migrations VS is not successful creating the Configuration with inheritance from my context-class.
Any suggestion on this issues? Using EF 4.3.1 and Code-First
This problem was resolved by installing EF 4.3.1 using the Package Manager Console. I had done a manual upgrade and for some reason that didn't do the trick.