Asp.Net Two Local DBContexts to One Azure DBContext - asp.net

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. :)

Related

ASP.NET Entity Framework code-first connection string for SQL Server mdf file, where is it and how do I change it?

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

EntityFrameworkCore for Sqlite not creating __EFMigrationHistory table

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.

Entity Framework Identity Connection String

I am a beginner and this is my first project with users.
When I look in the IdentityModels.cs class I find this code.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
What is the DefaultConnection?
Because I can create a user now just fine, without having done anything to any code, but where do my users go?
And when I put my site live, will it be okay, can I just leave all the Identity related code be?
Or should I make it so that it goes into the database I am currently using?
If so, how do I do that?
All other tips regarding Identity and users are also very welcome.
Thank you.
The DefaultConnection connection string that you are referring to is one that is used as a default by Entity Framework and if you haven't set it since creating the application, it's going to point to a LocalDB instance on your machine.
If you look under the <connectionStrings> section of your web.config file, you should see the name of the file that the actual database is stored in (it should be an *.mdf file and you should also see the name of the database) and you should be able to open it using any SQL Server database tool (or some editions of Visual Studio).
If you opened the database up, you should be able to see your actual users and other Identity information / tables :
It's unlikely that you would want to use this same approach when deploying an actual application, so you would just need to change your connection string to target your production database prior to deploying your application.

Flyway: non-empty schema without metadata table

Found non-empty schema "public" without metadata table! Use init() or set initOnMigrate to true to initialize the metadata table.
I'm using Postgres 9.2 with Postgis 2.0. This means that by default when I create a new database there will be a table created in public schema called spatial_ref_sys.
When I run flyway migrate on this database, I get the above error. Running init seems to create the public.schema_version table and mark version 1 as SUCCEDED without actually running the the migration file. I've also tried combinations of initOnMigrate with no success. Flyway is not configured to manage any schemas.
Any ideas on how I can run a migration in this scenario?
The title is somewhat contradictory, as the database is indeed not virgin as you installed, through the PostGIS extension, a number of objects in the public schema.
You can either
set flyway.schemas to a new schema, say my_app, which will then be created automatically by Flyway. Your application should then use this one instead of public (recommended)
set flyway.baselineOnMigrate to true or invoke flyway.baseline() against the public schema. This will work, but public will then contain a mix of both your application objects and the PostGIS objects
If you are using Gradle you can run
./gradlew -Dflyway.schemas=public flywayClean flywayMigrate
Where public is the name of the database containing the schema_versions table. That should delete the table and metadata as well as running the migrations to get it back up to date.
Caution!
This will delete all data in public schema
I think this error comes only with latest version of Flyway i.e. above 4.03. I didn't received in the earlier project but got it when I am using Flyway version 5.07 in my latest project. Putting the code here that resolve my issues
public class FlywayConfig {
#Autowired
DataSource dataSource;
#Autowired
Config config;
#Bean
public Flyway flyway(){
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource);
flyway.setSqlMigrationPrefix("V");
flyway.setLocations(new String[] { config.getSqlLocation() });
flyway.setBaselineOnMigrate(true);
// *******************flyway.clean(); ********************// this will wipe out the DB, be careful
flyway.migrate();
return flyway;
}
}
this work for me , i were figthin with the same problema a lot of time
my project was building on maven
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource);
flyway.setLocations("db/your_db");
flyway.setTable("name_of_schema");
next a added this line
flyway.setBaselineOnMigrate(true);
flyway.clean();
next this lines
MigrationInfo migrationInfo = flyway.info().current();
flyway.migrate();
and i let you the URL of my references from flyway.org
Flyway.org/documentation/commandline/baseline
In my case the problem started when I deleted all the rows in the table myschema.schema_version
./gradlew flywayInit did the trick and the error is not showed anymore.

exception after upgrade ASP.NET Identity to 2.0

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.

Resources