How to use Entity Framework code-first - entity-framework

I created some classes, and configured the connection string.
But still got an error:
Unhandled Exception: System.NotSupportedException: Model compatibility cannot be
checked because the database does not contain model metadata. Model compatibility
can only be checked for databases created using Code First or Code First Migrations.

Check the EF version you have, latest is 4.3.1.
You also need to configure a DbContext class. check this: http://msdn.microsoft.com/en-us/data/gg685467

i fixed it
by Run the ‘Enable-Migrations’ command in Package Manager Console.

Here is what worked for me if you are fine with deleting and recreating the database from scratch.
First, run the following commands from package manager console.
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
Next, delete the mdf and ldf files from the app_data folder of your project.
Here comes the critical part. Usually you will run update-database. If you do that the exception will still be thrown.
DO NOT Run update-database. INSTEAD directly run your project code. The EF will recreate the database.
These steps worked for me. Let me know if this helps you.

Related

I deleted Migrations file and folder .I try again dotnet ef migration add initial but I see Built failed

I am working on an ASP.NET Core MVC app. I deleted the Migrations file and folder. I try again using .NET EF Core migration and adding initial, but I see the build failed. How can I do this?
Your question does not explain many things like did you created any other class or namespace in migrations folder and accidentally deleted it as well.
Build failed error is caused by some missing file, reference or some syntax error.
Check you Error List tab in visual studio.
I use to write my command ">dotnet ef migrations add initial" in CLI and I could see only "Build Failed" . Then I used Package Maneger Console "PM> add-migration initial" and take more description. when I fixed errors I am succed successful
[Link]https://www.entityframeworktutorial.net/efcore/entity-framework-core-console-application.aspx

How to downgrade/rollback migration in Universal Windows Platform with Entity Framework using Package Manager Console?

I modified a property in the model and it turned out it is not supported by the version of SQLite. This is the error. {"SQLite does not support this migration operation ('DropColumnOperation'). For more information, see http://go.microsoft.com/fwlink/?LinkId=723262."}
So I decided to roll it back by using the command Update-Database Migration "MyFirstMigration" but an error shows up on the console which states Update-Database shouldn't be used with Universal Windows Platform apps. Instead, call DbContext.Database.Migrate() at runtime.. This code recommended is already the code executed at the first run of the application that generates the first error above.
I am really going into circle here. Can someone suggest how I can rollback/downgrade MySecondMigration ti MyFirstMigration?
Can someone suggest how I can rollback/downgrade MySecondMigration ti MyFirstMigration?
For the same DbContext, just execute Remove-Migration command on your package manager console, it will remove the last migration of this DbContext. It is your MySecondMigration which will be removed and only MyFirstMigration left.
Update-Database shouldn't be used with Universal Windows Platform apps. Instead, call DbContext.Database.Migrate() at runtime
For this, just as this error shown, DbContext.Database.Migrate() applies any pending migrations for the context to the database, include what Update-Database did (Updates the database to a specified migration). By testing on my side, for the same DbContext, every new migration is the updating based on the old one. DbContext.Database.Migrate() will apply all the migrations for updating. If you don't want the latest update, just remove it for roll back.

How to cope with "No data stores are configured"?

I am currently playing with beta4 of EF7 using the blank ASP.NET web project template.
After having kicked off the existing migration, resulting in the tables being created in the localdb, the following occurs:
Strangely, when I clean up the migration-folder, including removing ApplicationDbContextModelSnapshot.cs and I run
dnx . ef migration add twice, I get the following error:
dnx : System.InvalidOperationException: No data stores are configured. Configure a data store by overriding OnConfiguring in your DbContext class or in the AddDbContext method when setting up services.
The second migration is not created. When I review the created migration it contains all tables whereas the database is already provisioned, so you should expect the migration being empty.
Then, when I remove the first migration and run the add migration command again more than once, all the migrations are correctly created, i.e. as empty files.
Can someone explain this to me? Is this expected behavior or is this a bug in beta4?
Tip for people coming from former EF-versions:
* Don't use the K command framework anymore.
* Don't use the Add-Migration cmdlets anymore.
Both have been replaced by dnx . (dot). (dnx = .NET execution environment)
Some references:
https://github.com/aspnet/EntityFramework/wiki/Entity-Framework-Design-Meeting-Notes---September-11,-2014
http://jameschambers.com/2015/05/project-k-dnvm-dnx-dnu-and-entity-framework-7-for-bonus-points/
Remove the constructor of ApplicationContext. It is a temporary workaround to enable deployment, but it interferes with the Migrations commands.

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 does not function with remote sql server databases in shared hosting

It looks like CodeFirst stops doing its homework when it doesn't have full control of the database (I suppose).
The scenario is a web site hosted on Arvixe.com (or I suppose any other shared hosting server), where I have to create databases only from their control panel (and NOT with Sql Server Management Studio, just to say...).
Once created an empty database, I register a connection in the web site, and I use it to generate database from poco objects like in:
add-migration m1 -targetdatabase myconnection
This generates correctly my FIRST migration, that I can apply without problems with
update-database -targetdatabase myconnection
The first concern, not too important, is that since the database is existing, it will NOT issue the Seed command, so I have to insert my first records by hand, but this is not a great problem.
Then I change my poco objects, and I need to update the database, but when I issue ANOTHER
add-migration m2 -targetdatabase myconnection
it gives the error:
System.Data.Entity.Migrations.MigrationsPendingException: Unable to generate an explicit migration because the following explicit migrations are pending: [201111081426466_m1]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
This is really strange, since if I look at the database, I can see even the table __MigrationHistory, but then it looks like it cannot recognize it...
Anyone with the same problem, or some good tip to where investigate?
Thanks in advance,
Andrea Bioli
I had this problem. I was able to resolve it by providing a connectionString and a connectionProviderName parameter to both the Update-Database and the Add-Migration commands.
If you have many projects in your solution with multiple config files, Package Manager seems to be confused. In my case, I had one project selected as the default project for Package Manager Console, but it was pulling the connection string from the Visual Studio solution default start-up project instead.