I have a web app that I developed through this tutorial:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/introduction-and-overview
This tutorial put two DBContext (ApplicationDbContext and MyDBContext) with their respective databases with EF and Code First, I published in Azure several months ago and everything works well, both locally and in Azure. From the beginning I noticed that Azure only manages a database. In this database Azure are all the tables of the two DBContexts and as I said everything works well. I have done dozens of Migrations, only in my own WebApp tables (MyDBContext)
Now I want to add fields to a table of the AplicationDBContext, specifically to the AspNetUser table, so I modify the following code
public class ApplicationUser: IdentityUser
{
/// My New Field
public bool Disabled {get; set; }
public ClaimsIdentity GenerateUserIdentity (ApplicationUserManager manager)
{
var userIdentity = manager.CreateIdentity (this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public Task <ClaimsIdentity> GenerateUserIdentityAsync (ApplicationUserManager manager)
{
return Task.FromResult (GenerateUserIdentity (manager));
}
}
Then I implemented:
Enabled-Migrations -ContextTypeName ApplicationDbContext -MigrationsDirectory Migrations \ ApplicationDbContext
Add-Migration -ConfigurationTypeName MyWebApp.Migrations.ApplicationDbContext.Configuration "AddFldAspNetUsers"
Update-Database -ConfigurationTypeName MyWebApp.Migrations.ApplicationDbContext.Configuration
Locally everything works fine, but when I publish in Azure I get the following error:
Server Error in '/' Application.
The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database
I do not know how to solve it, I need help:
I have faced the same problem recently. The reason behind the problem you have scaffold the migration but haven't updated the Identity database tables in Azure.
Please follow the below points
Before publishing, in publish window go to settings, there you could
find ApplicationDbContext under Databases section.
Give a tick to the check box Execute code first migrations(runs on
application start) option. Try to re-publish it again. :)
I am launching my asp.net application and am having issues with some databases that were created locally. I need to change their connection string for the program to point to my new online SQL Server database but I can't find any way to do that. I created these databases locally using the Entity Framework code-first scaffolding. This is my code for the db context:
public class SubjectDbContext : DbContext
{
public DbSet<Subject> SubjectDatabase { get; set; }
}
And I made it into a .mdf using this method:
Which automatically generates the database using constructors (according to https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#localdbtosse). That's what I was able to figure out.
I really need to find these connection strings so I can change them because otherwise I don't know how to get my published application online to access its respective databases.
Remaking these databases is not really an option. So I need to find AND change the connection strings for them. Now the connection strings are not in the web.config file. In fact deleting all the connection strings in the web.config file does not stop these databases from working locally. So they must be stored somewhere else.
How can I change these connection strings. If I can't my application won't work online.
The closest post I could find to this question was:
Code first: Where's the connection string & the Database?
but it doesn't answer the question. Thanks for any help or links.
The default Connection string gets added in Web.config by the name "DefaultConnection".
And the database files gets created under App_Data folder of your application.(Click 'Show All files' to see the databases file or browse to the App_Data folder path in explorer).
This is how you do migrations after having the DefaultConnection set to your new server:
Change SubjectDbContext to as below, adding constructor:
public class SubjectDbContext : System.Data.Entity.DbContext
{
public SubjectDbContext() : base("DefaultConnection")
{
}
public DbSet<Subject> SubjectDatabase { get; set; }
}
Run command in Package Manager Console:
Enable-Migrations -ContextTypeName SubjectDbContext -MigrationsDirectory Migrations\SubjectDbContext
It will create Configuration.cs in Migrations/SubjectDbContext folder
Set AutomaticMigrationsEnabled = true; in Configuration constructor. Can add seed code if required.
Run the below command in Package Manager Console, to create the database and its tables:
Update-Database -ConfigurationTypeName [Replacewith namespace].SubjectDbContext.Configuration –Verbose
Before I explain my issue, I have some experience with entity framework 5 and 6 code first migrations, running add-migration/update-database and a few more specific commands from the Package Manager console. All of the migration history was handled out of the box in the __MigrationHistory table.
I am now writing a UWP app and using EntityFrameworkCore sqlite. The app is set up to scaffold new migrations and does so correctly.
When applying migrations the app needs to automatically deduce, on install and first startup, if the database exists, and the current database migration version. It can then apply the relevant migration procedures, including creating the database if required.
Currently, I attempt to perform the migrations in my DbContext on startup:
public class MyContext : DbContext
{
public DbSet<SomeEntity> MyEntities { get; set; }
static MyContext()
{
using(var db = new MyContext())
{
db.Database.Migrate();
}
}
This works perfectly for a new app on first startup. On second startup however, or after the addition of a new migration, the Migrate() method fails as the tables it is attempting to create already exist.
SQLite Error 1: 'table \"MyEntities\" already exists'
This error comes from rerunning the migration that has been previously applied. The database itself needs to be aware of it's migration history as was previously handled with __EFMigrationHistory. Currently this table is not being created for me.
I am suspecting that I need to manually build a solution to this, maybe creating my own __MigrationHistory table and keeping it up to date, as per this post here
I wondered what solutions people have used for this issue, or if there is anything out of the box that I'm being silly and missing.
Let me know if more detail needed.
I solved this in a manner of speaking but I'm still not sure why the __MigrationHistory table was not automatically generated...
I couldn't find any evidence of other people struggling with this issue in UWP apps, so it is likely project specific and something caused by how the solution was set up.
Anyway, the changes I made:
I created a MigrationHistory model and added it as a DbSet to my DbContext.
Model
namespace MyApp.Shared.Models.Infrastructure
{
public class MigrationHistory
{
public string MigrationId { get; set; }
public string ProductVersion { get; set; }
}
}
DbContext additions
public class MyContext : DbContext
{
public DbSet<MigrationHistory> __MigrationHistory { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
#region Primary Keys
modelBuilder.Entity<MigrationHistory>().HasKey(mh => mh.MigrationId);
At this stage, on running add-migration entity framework attempted to create the __MigrationHistory table. This would result in an error if I ran my application, as applying the migration would result in the error:
SQLite Error 1: 'table \"__MigrationHistory\" already exists'
So I added the following code to my MyContextModelSnapshot class
modelBuilder.Entity("MyApp.Shared.Models.Infrastructure.MigrationHistory", b =>
{
b.Property<string>("MigrationId")
.ValueGeneratedOnAdd();
b.Property<string>("ProductVersion");
b.HasKey("MigrationId");
b.ToTable("__MigrationHistory");
});
Once it is in the snapshot, it can stay there, and it acts to prevent entity framework attempting to add this table in future migrations.
On startup my app now runs
using (var db = new Assessment.Data.WindowsUniversal.AssessmentContext())
{
db.MigrateDatabase();
}
And it works perfectly, consulting the table and applying migrations where necessary.
I feel like this is a solution to a problem that doesn't really exist, and that is of my own making, but I'll leave this here in case it's relevant to somebody else.
As far as i've come up with while having your same issue, i found out the debug database (inside your \bin\Debug folder) won't have the __EFMigrationsHistory table, while the production database (root of your launching project) has it.
Maybe could be of help for somebody else.
I encountered the same issue with Sqlite In-Memory databases in my Tests. I have found the following thread https://github.com/dotnet/efcore/issues/4922. The point is ones all connections to the database are closed, the database is being removed from the memory. I have not solved the issue yet as I started using physical databases instead. But I will update my answer ones I find the solution.
My problem is even if I call db.Database.Migrate() first time without any other connections opened before, it still throws such error.
my project: VS2013, Entity Framework, Web forms, database first, Identity
I updated all NuGet packages of my project today (2014-4-15). Among them, Identity is upgraded to 2.0.0.0.
I thought things were going good, but unfortunately when I run the application, the following statement gives an exception.
namespace xxx.Models
{
// You can add User data for the user by adding more properties to your User class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("MyConnection")
{
}
}
...
}
The exception information is as follows. It asks me to do Code First Migration. But my project is a Database First webforms project. How can I solve this problem? Thanks!
An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Identity.EntityFramework.dll but was not handled in user code
Additional information: The model backing the 'ApplicationDbContext' context has changed since the database was created.
This could have happened because the model used by ASP.NET Identity Framework has changed or the model being used in your application has changed.
To resolve this issue, you need to update your database. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=301867).
Before you update your database using Code First Migrations, please disable the schema consistency check for ASP.NET Identity by setting throwIfV1Schema = false in the constructor of your ApplicationDbContext in your application.
public ApplicationDbContext() : base("ApplicationServices", throwIfV1Schema:false)
You need to disable the schema consistency by doing what the error says. This is one time thing that happens when you upgrade from version 1.0 to 2.0.
public ApplicationDbContext() : base("MyConnection", throwIfV1Schema:false)
Next step - do the migrations.
Everything should work after that and you can remove this throwIfV1Schema:false
You can also take a look at this for more info
The problem is here :
public class ApplicationUser : IdentityUser
{
}
I think you should change to partial class to extend entity in Entity Framework. The reason is that EF will generate proxy class for each entity to connect to database.
The partial class should be write in the same namespace.
I am trying to replicate an example found on MSDN. I am using ASP.NET and EF 4.1 (CTP?). I've used NuGet to install the EntityFramework package.
I am getting this error: The provider did not return a ProviderManifestToken string ...
and the database is never created.
Here is my connection string:
<add name="HospitalContext"
connectionString=
"data source=.\SQLExpress;initial catalog=NewTestDB;integrated security=True;"
providerName="System.Data.SqlClient"/>
Here is my code:
var pat = new Patient { Name = "Shane123132524356436435234" };
db.Patients.Add(pat);
var labResult = new LabResult { Result = "bad", Patient = pat };
int recordAffected = db.SaveChanges();
Here is my context:
public class HospitalContext : DbContext
{
static HospitalContext()
{
Database.SetInitializer(new HostpitalContextInitializer());
}
public DbSet<Patient> Patients { get; set; }
public DbSet<LabResult> LabResults { get; set; }
}
public class HostpitalContextInitializer :
DropCreateDatabaseIfModelChanges<HospitalContext>
{
protected override void Seed(HospitalContext context)
{
context.Patients.Add(new Patient { Name = "Fred Peters" });
context.Patients.Add(new Patient { Name = "John Smith" });
context.Patients.Add(new Patient { Name = "Karen Fredricks" });
}
}
This is a fully patched SQL 2008 system, with VS 2010 SP1.
I was getting this error and tried a few of the earlier suggestions. Then I checked the Inner Exception and noticed I was getting a simple SQL login failure for the user. Just something else to check.
This can happen sometimes when you place the connection string within the app.config of the wrong project in Visual Studio.
For example, I got this problem in EF 4.1 (the released version) project + WCF Data Service project and I noticed that I didn't have a connection string specified in the Data Services Project, where it was being used.
I had the same problem, and I add the below code just after the instance of my context (onload by exemple)
context.Database.Connection.ConnectionString = #"Data Source=.\SQLExpress;Initial Catalog=Test;Integrated Security=True";
I was having same error, and actually it was login failed for the specified server. I removed "Integrated Security" attribute from the config connection string and it worked.
I had a similar issue with the MvcMusicStore app. I changed a line in the Web.config from
"Instance=true" to "Instance=false". It sometimes works without this tweak but I don't know what causes the difference. Reading this
http://msdn.microsoft.com/en-us/library/ms254504.aspx didn't really help.
By some certain reason of permission, EF can not create database connection.
I had faced the same problem all of one day. Finally I had tried following solution and it worked:
a/ Open IIS (I'm using IIS 7)
b/ Open advanced settings of appool which web site was using (Ex: DefaultAppPool)
c/ Look at Process Model group, change Identity value to "Localsystem"
Hope it work with you.
I was just having the same problem...
the solution that worked for me was:
run the client network configuration tool (type cliconfg in Run)
and make sure TCP/IP is enabled..
I finally cracked it - after a slight wild goose chase thinking it was due to permissions.
Revelation: USE SQL PROFILER
(Note: I recently downgraded from EF6 to EF5)
Using SQL Profiler I quickly found the last SQL executed before the reported failure:
SELECT TOP (1)
[Project1].[C1] AS [C1],
[Project1].[MigrationId] AS [MigrationId],
[Project1].[Model] AS [Model]
FROM ( SELECT
[Extent1].[MigrationId] AS [MigrationId],
[Extent1].[Model] AS [Model],
1 AS [C1]
FROM [dbo].[__MigrationHistory] AS [Extent1]
) AS [Project1]
ORDER BY [Project1].[MigrationId] DESC
Well look at that - something to do with migrations. It's looking in __MigrationHistory table - which I hadn't even realized it had created (I had already wiped out Migrations in my CSPROJ) and cleared that out.
So I pull up the rows for that table and see that it is tied to a specific product version (v6).
I actually downgraded from EF6 (which I didn't intend to install in the first place) to EF5 (which is more compatible with scaffolding) and that when the problems began.
My guess is that the Model (<Binary data>) column is not backward compatible - hence the The provider did not return a ProviderManifest instance error since it was unable to decode it.
I didn't have anything to lose and just wiped out this table completely and ran Update-Database -Verbose and then was back up and running.
If you're in an advanced environment or already in production then wiping out this table may not be the solution, but this way allowed me to get right back to work.
In using Visual Studio 11 Beta with EF4.1 and ASP.NET MVC, I nearly pulled my hair out until I found
http://connect.microsoft.com/VisualStudio/feedback/details/740623/asp-net-mvc-4-default-connection-string-improperly-escaped
To fix my problem, I went into Application_Start and changed
Database.DefaultConnectionFactory = new SqlConnectionFactory("Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
to
Database.DefaultConnectionFactory = new SqlConnectionFactory(#"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
This error is only present while the .edmx file is open and disappears as soon as the file is closed again.
This quote from CodePlex , this worked with me (visual studio 2013 /MVC 5)
One other thing to consider if you're using EF Code First is that it sometimes doesn't automatically create the backing database to your DbContext class. The solution is to add your own connection string - you can use the connection string that may be present to handle the user/registration database that backs the Simple Membership Provider, as a template.
Finally, you will need to add a default constructor for the DbContext class you created:
public ChaletDb():base("ChaletConnection")
{
}
Here, the name of the connection string as you entered in your web.config file is used to direct the DbContext to create the database.
Very occasionally, I've had to manually create the database (in SQL Server Management Studio) which prompted it to work.
I have multiple projects in a solution and added EF to each project in different times. On some machines it was working and on some it failed with aforementioned error. It took me a while to notice that some of my project's app.config had this:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
This is ok if you use LocalDb (new "sql express" like), but completely wrong if you don't have that specific server installed and use a regular SQL.
Solution: Remove the above code.
This is because connection to SQL server failed.
Make sure the User Account under-which you are running the process have access to SQL Server.
If you have generated the DbContext from parent thread (like using dependency Injection) and then if you are impersonating another user then this error would occur. The solution would be to generate the DbContext inside the new thread or new Impersonation context.
I just closed all instances of Visual Studio and reopened my solution.
I don't know what really happened, but I had the same solution opened from two different local workspaces (one with my local changes, one with the unchanged repository source code). I work with a postgres DB, Entity Framework 6, Visual Studio 2013 and ASP.NET MVC 5.
I had a error for entity framework, but none of the above answers ended up fitting into the solution that finally worked.
My EntityFramework Code First Models and DataContext were in a Separate project from my WebAPI Main Project. My Entity Framework Project somewhere down the line of coding was set as the startup project and therefore when I was running a migration I was getting “The provider did not return a ProviderManifestToken string” ... connection issue.
Turns out that since the ConnectionString to the DB is located in the Web.config file in WebAPI Main project, that when I was running a migration the connection string was not being retrieved. By setting WebAPI project as my startProject I was able to successfully connect.