EF6 "No migrations have been applied to the target database." - asp.net-mvc

In an mvc5 application, I created a CodeFirst data model, and performed several migrations on it.
I then refactored my project, and moved all the data/migrations classes to a new project, which is referenced by my presentation tier.
The dbcontext successfully connects and performs read/write operations on the DB after the project change.
When I made a minor change to the model and ran add-migration, the EF created a migration with the code to create the database from the beginning, like it didn't "see" the existing tables.
Of course, when i ran
Get-Migrations -ConfigurationTypeName ConfigurationDbContext
i got
No migrations have been applied to the target database.
The __MigrationHistory in the DB is intact and the migrations/configuration classes namespaces didn't change. Also, apparently, the ConnectionString is OK, otherwise he would have trouble working with the db and i would get the "The model backing the context has changed since the database was created" or similar error.
EDIT:
As suggested in the comment, I specify the exact connection string in the DbContext constructor, and not the connectionstirng name in web.config, as it was in the original mvc project.
Still no history/changes in the db when running Get-Migrations and update-databse.
when I run Get-Migrations -ConfigurationTypeName My_Namespace.Migrations.ConfigurationDbContext.ConfigurationDbContext
I get
No migrations have been applied to the target database.
If I try to specify the connection string
Get-Migrations -ConfigurationTypeName My_Namespace.Migrations.ConfigurationDbContext.ConfigurationDbContext -ConnectionString "Server=my_server;Initial Catalog=my_catalog;User Id=my_user;Password=my_pass" -ConnectionProviderName="System.Data.SqlClient" -verbose -debug
the PM gets stuck on >> sign, until I restart or clear the window...
if I omit the ConnectionProviderName="System.Data.SqlClient", the console asks me to enter it, and after I enter, it shows connection to the correct db,
Target database is: 'my_catalog (DataSource: my_server Provider: System.Data.SqlClient, Origin: Explicit)
but still no migrations...
No migrations have been applied to the target database.
Why can it be and what can be done to further investigate/resolve this issue?
EDIT 2:
the constructor of my dbcontext is simple:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base(
"Server=my_server_name;Initial Catalog=my_db_name;UserId=my_username;Password=my_password"
)
{}
public DbSet<Model1> Model1Entities { get; set; }
public DbSet<Model2> Model2Entities { get; set; }
public DbSet<Model3> Model3Entities { get; set; }
}
it is based on IdentityDbContext as in the template mvc5 applicaiton, because I didn't want to create a different dbcontext for it.
and the ConfigurationDbContext is automatic
internal sealed class ConfigurationDbContext : DbMigrationsConfiguration<ApplicationDbContext>
{
public ConfigurationDbContext()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ApplicationDbContext context)
{
}
}
Thanks!

Well, the answer is that somehow during the refactor the namespace of ConfigurationDbContext changed from
demo10.Migrations.ConfigurationDbContext
to
demo10.Migrations.ConfigurationDbContext.ConfigurationDbContext
and the ContextKey column of the __MigrationHistory table should be the ConfigurationDbContext namespace (you can omit the DbContext, like to have
demo10.Migrations.Configuration
in the table for
demo10.Migrations.ConfigurationDbContext
namespace).

Leaving an answer here as I had a similar problem that wasn't solved by this:
I had the password wrong in the app.config I was using against a different environment. Get-Migrations doesn't give you an error about failed credentials, it just tells you "No migrations have been applied to the target database", which is hugely misleading.
Hopefully someone else who comes across this will discover it's as simple as a typo in their connection string!
edit: the irony of typo-ing the word typo in an answer about my typo.

I've run into issues in development having the __MigrationHistory table open in SQL server Management Studio...
After closing the table (which was NOT open for edit, just select), somehow fixed everything.

Chiming in with an edge case of my own: check to see if your DB is in mixed mode or purely in Windows Auth mode.
Had a 2014 install go sideways such that sa was disabled and there was no Windows account authorized (client had a hosting upgrade to 2014, so I had to match it). I managed to stand it back up and regain Windows account access (real edge case voodoo shit), but didn’t realize it was stuck in Windows Auth mode only. Once I switched it back to mixed mode, I suddenly had a connection again. D’oh!

This happened to me just now and the issue was that my sa password had expired and needed to be reset. I was still logged in from a previous session so I could run queries no problem but when I disconnected and reconnected I had to reset my password! Took me an hour to figure that out though :/

I had this problem when i split the code into multiple projects. Solved by seting the default project of the solution to the one that have the correct connection string.
Get the hint by running the command:
get-migrations -Verbose
eflocation\ef6.exe migrations list --verbose --no-color --prefix-output --assembly dataproject \project.dll --project-dir dataproject\ --language C# --data-dir defaultproject\App_Data --root-namespace dataproject --config defaultproject\Web.config
The Web.config or app.config file that you see after running the command should be taked from the default project.

I had the same problem after I changed the name of my project. I had also recently rebooted the server.
So, I had to do two things to solve the problem:
Start the SQL Server service
Create an Update query for the
__MigrationHistory table to change the value of the ContextKey column from Old_ProjectName.Migrations.Configuration to New_ProjectName.Migrations.Configuration.
That sorted it for me.

Related

EF not seeding database on creation

I am using Entity Framework to create and seed my database using Code First and the MigrateDatabaseToLatestVersion initializer. The issue I am having is when I launch the ASP.NET MVC app without a database create EF will create the database but will not seed on the first run through. If I kill iisexpress and relaunch the app after creating the database my seeds go in fine. I would expect my seeds to be ran after the database gets created but I don't even hit a break point in my seeds method on the first run through. I hit break points on the second run through without problems but it is annoying to have to run the app twice after killing the DB just to get my seeds to work.
Below is my Configuration class:
public sealed class Configuration : DbMigrationsConfiguration<CompassDb>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(CompassDb context)
{
ModuleSeed.Seed(context);
PermissionGroupSeed.Seed(context);
var permissions = PermissionSeed.Seed(context);
var roles = RoleSeed.Seed(context, permissions);
UserSeed.Seed(context, roles, permissions);
OcmPluginSeed.Seed(context);
SCACSeed.Seed(context);
ModuleConfigurationSeed.Seed(context);
}
}
I am calling this in my Global.asax file.
Database.SetInitializer(new MigrateDatabaseToLatestVersion<CompassDb, Configuration>());
using (var db = new CompassDb())
{
db.Database.Initialize(true);
}
I did have a query to get a version number from the db on page load to create the database but calling the initializer directly seems a little cleaner. I was having the issue before when I was making a DB call through EF as well. I moved away from the DB call because I am only using EF for the automatic DB creating and migration then I switch to Dapper for any database communication.
I found this post here where people were having the same issue as me but it doesn't seem like it was ever resolved.
UPDATE
I found out that the issue is related to my migration files. I updated the primary keys of all my models from int to long and had to delete my current migration files. After deleting the files everything started working as normal, the database would be created and seeded on the same request. I then created my initial schema migration and am back at the same issue where the database does not seed until the 2nd time launching the site. I am using ELMAH in the project and have to update the first migration file to execute the sql file that is included when installing ELMAH via nuget. This could be related to the issue and I will do more testing to see if this is the cause.
I think I had the same or similar problem. Try to make a manual initializer. It's clean, simple and short. See this example:
Public Class CustomDbInit
Implements IDatabaseInitializer(Of MyContext)
Public Sub InitializeDatabase(context As MyContext) Implements System.Data.Entity.IDatabaseInitializer(Of MyContext).InitializeDatabase
If Not context.Database.Exists Then
context.Database.CreateIfNotExists()
' Some other processes, such as WebMatrix initialization if you're using SimpleMembership like I do
End If
End Sub
End Class
Then on the Global.asax Application_Start method, initialize it like this:
Dim context As New MyContext()
If Not context.Database.Exists Then
Database.SetInitializer(New CustomDbInit())
context.Database.Initialize(False)
End If

How to update database model on a deployed asp mvc web site without losing data

How to update database schema (model) in asp mvc website after it is deployed, without losing any previous data?
I have just deployed an MVC5 website to azure web site. Everything is fine, thus I started to uploading some data. Then I figured out something that I needed to update. It is simple, I just want to make a slight change in its database schema.
In local machine (development stage), we can just run
Update-Database
on package manager console. And here is the question? how to do the same idea to the published version? I have not tried to re publish my solution, fearing that the data will be lost (the data is plenty, too much to re upload).
I am using entity framework 6 code first with migration enabled:
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
All I want to do is just adding an attribute to one of the data row:
public class MyViewModel
{
public string Name {get;set; }
public string Content { get; set; }
}
to:
public class MyViewModel
{
public string Name {get;set; }
[AllowHtml] //ADDING THIS ONLY
public string Content { get; set; }
}
Thanks.
you can, among other solution, use this
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BlogContext, Configuration>());
where BlogContext is your context and Configuration is the configuration class (the one descending from DbMigrationsConfiguration<T>) generated by code first.
Of course you have to republish your application (at least binary part).
Please also read http://msdn.microsoft.com/en-us/data/jj591621.aspx, specially the last paragraphs.
Welcome to the scariness that is Code First Migrations in a production environment! One thing to note, if you enable automatic migrations, you can never revert the migration. Instead, it's recommended that you don't do automatic migrations. Instead, from your console, run add-migration "migrationName". This will add a migration to your migrations folder with an up and a down method, where you can see all the changes that are related to that migration. You can see what sql will be run against the database by running update-database -script. The changes will not actually be run, but you can see what sql is generated. Here is a good walkthrough on Code First Migrations and deployment and all the changes that are necessary in the web.config file.
I believe that allowing data loss is turned off by default when you use automatic migrations.

EF4 database first configurable schema

I have one issue I am trying to resolve for days now, but I can’t get the right approach.
I am using EF4 and I have one application where I use DataBase First, which originally created the ObjectContext, and I donwloaded the DbContext generator and generated it.
The thing is, I need the application to be able to get the database SCHEMA from some configuration file, instead of ALWAYS using the “dbo” default.
I was trying to use the “ToTable” method (so I can specify the schema) in the “OnModelCreating” overload method but as this article sais, as I am using DataBase First, that method is not called.
How can I make the schema name configurable?
Is that even possible?
I read this article too, where it says I can combine database first with code first but I can’t see how to do that if I can’t use the "OnModelCreating" method.
Thanks a lot in advance!!!
I don't know about configuring schema. However if you want your db first approach to changed to the code first, just change the string parameter of your DbContext constructor.
Suppose that you have the following DbContext that EF Db first created for you:
public class MyDbContext : DbContext
{
public MyDbContext()
: base("Name=DefaultConnection")
{
}
// DbSets ...
}
change that to the following to start using code first and all magic tools of it (migration, etc.):
public class MyDbContext : DbContext
{
public MyDbContext()
: base("YourDbFileName")
{
}
// DbSets ...
}
It causes that EF creates a new connection string using SQL Express on your local machine in your web.config file with the name YourDbFileName, something just like the early DefaultConnection Db first created.
All you may need to continue your way, is that edit the YourDbFileName ConStr according to your server and other options.

Asp mvc 3 noobie: Why is the code-first method not building my DB on sql server?

I am an ASP MVC 3 noobie who has done a few tutorials. Now I'm trying to build a site. All of the tutorials on the microsoft website emphasize the code-first approach: you define your model with code and then create a datacontext and then the entity framework creates/manages the DB based on your code.
I set up an Employees class and a DataBaseContext class that inherits from DbContext. I added a connection string to Web.config connection string that successfully links DataBaseContext to an already existing empty DB on SQL server. EDIT= That was the problem. See my answer below
But when I try to run the Employees controller created thru scaffolding, I get this error
Invalid object name 'dbo.Employees'.
Description: An unhandled exception occurred during the execution of...
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Employees'.
I followed this post SqlException (0x80131904): Invalid object name 'dbo.Categories' and realized that if I create an employees table on the DB, this excpetion goes away (I get a new one saying that the column names are invalid).
But I thought the whole point of MVC 3 is that the framework will make the DB for you based on the code.
Maybe I need a line of code in the Global.asax Application_start() to create the database? Here is my application_start method:
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterGlobalFilters(GlobalFilters.Filters)
RegisterRoutes(RouteTable.Routes)
End Sub
Here is the code for Employee:
Public Class Employee
Property EmployeeID As Integer
Property First As String
Property Last As String
Property StartDate As DateTime
Property VacationHours As Integer
Property DateOfBirth As DateTime 'in case two employees have the same name
End Class
Here is the code for the DB context:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
What am I missing?
By default EF uses DropCreateDatabaseIfModelChanges<TContext> database initializer. Accordingly to the MSDN:
An implementation of IDatabaseInitializer<TContext> that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created. This is achieved by writing a hash of the store model to the database when it is created and then comparing that hash with one generated from the current model.
Since the database was created manually, EF can't find the hash and decides do not perform any further initialization logic.
You might want to look into this article, same question successfully answered already.
Or it can be this (also resolved successfully)
Answer to your problem is most likely one of the two.
Hope this will help you
Does the name you're specifying for your connection string match the name of your database context?
For example:
Context
var myDbContext = new MyDbContext();
Connection string
<connectionStrings>
<add name="MyDbContext" connectionString="YOUR.CONNECTION.STRING" providerName="System.Data.SqlServer" />
</connectionStrings>
Try and see if this post I wrote about DbContext with MVC works for you: Code-First
Not a lot to be done to get this to work, but there are a few things that are easily missed that will cause a bunch of head aches.
hope this helps
I had already created a database with that name on SQL server. Once I deleted the existing database, the code first framework created the tables for me like it was supposed to. It seems like if the database already exists, the framework won't set up the tables for you. It wants to create the whole DB from scratch.
You were using AdventureWorks Database?
It has it's own schema assigned to the employees table. HumanResources.Employees and not the default dbo.Employees.
Even though I've identified the problem, I don't know the solution to using the database as configured with the HumanResources schema.
Anybody know?

Entity Framework is trying to create a database, but its not what I want

I have a small asp.net mvc4 application (working fine in my local machine), that uses entity framework v4.1.0.0 with ADO.net DbContext Generator.(SQL Server 2008 r2)
I am adding newer versions of dlls required through the "Add Deployable Dependencies..." context menu in Visual Studio 2010.
I have a shared hosting with godaddy.com, I have uploaded the files to server and created the database, now here comes the problem.When I try to browse my site I get the following error:
CREATE DATABASE permission denied in database 'master'.
I looked this up around and found out that this error was caused by EF code first trying to create database.but i do not want EF code first to recreate the database, how do i turn off this automatic database creation altogether? I have no intentions of using the code-first feature whatsoever.
Please help.
put this code into the Application_Start() method of Global.asax or constructor on your DbContext class
Database.SetInitializer<MyContext>(null);
If you want to recreate database when POCO domains are changed, use following code instead of above
Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
If you are using EF Migrations, this is what you set for it:
public sealed class DbConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
public DbConfiguration()
{
AutomaticMigrationsEnabled = false;
}
}
But this doesn't answer the question on EF Code First itself. If the database already exists, then EF will not try to create it. So you just need to point it to an existing database. And to make sure the connection string name is the same as the name of the database context. If it is not, you need to provide it to it with some overrides:
public class DatabaseContext : DbContext
{
public DatabaseContext()
: base(ApplicationParameters.ConnectionStringName)
{
}
public DatabaseContext(string connectionStringName)
: base(connectionStringName)
{
}
}

Resources