exception after upgrade ASP.NET Identity to 2.0 - asp.net

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.

Related

Asp.Net Two Local DBContexts to One Azure DBContext

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

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.

How to inject dependencies using Ninject In ASP.NET WebForm?

I have a fair idea of using the Repository Pattern and have been attempting to "upgrade" our current way of creating ASP .Net websites. So i do the following
Create a solution with a class project called DataAccessLayer and another class project called BusinessLogicLayer. Finally a 3rd project which is my ASP .Net website (a normal site).
I add a dbml file to the DAL and drag a table, then in my BLL i add an interface and a class which implements this interface:
My interface
namespace BLL.Interfaces
{
interface IUser
{
List<User> GetAllUsers();
}
}
In my class
namespace BLL.Services
{
public class UserService : BLL.Interfaces.IUser
{
public List<User> GetUsers()
{
throw new NotImplementedException();
}
}
}
I know the code is not fully completed, but there for illustrative purposes.
So i right click the BLL project > Manage NuGet Packages > Searched for Ninject and found a few. I was overwhelmed with the number of entries returned after after further research i am lost in how to add Ninject to a normal ASP .Net website? Specifically which addin i require? As there are many MVC and reading further i think im a little confused.
I was trying to add it to the BLL project as thats where i THINK it should go so i can register my services in there.
Could anyone guide me in what i need to so in order to use Ninject entries but im not using MVC?
Install Ninject.Web either from "Package Manager Console" or NuGet.
Version is 3.2.1 as of this writing.
OR
It will install the following 4 packages -
Sample Service Class
public interface IUserService
{
List<string> GetUsers();
}
public class UserService : IUserService
{
public List<string> GetUsers()
{
return new List<string> {"john", "eric"};
}
}
Then add binding to ~/App_Start/NinjectWebCommon.cs.
In code behind page, property inject using [Inject] attribute.
In Addition in answer by win I would advise people not to get confused by using Constructor based injection in ASP.NET Webforms as Web Forms doesn't support constructor based injection simply. In default configuration they only support Property based Injections as already demonstrated by Win.

SPA Template VS2013 custom properties IdentityUser

I'm trying to add custom properties to the Identity User 2013 Spa Template. The Identity User model is not in the project when I F12 I get the model in the assembly which is not editable. I have read the tutorial to add a birth date to the Identity model however this example speaks about changing the Identity User model from a Web Forms prospective and it seems to have a UserIdentity model to edit. How do I add custom properties to the AspNetUser table?
I found the same. Most of the SPA template resources online seem to relate to the earlier (VS2012) version of the template which is quite confusing. However, by comparing the code generated by the MVC template I worked out what I needed to do which was.
In the Models folder create your own "ApplicationIdentity" and "ApplicationDbContext" classes. Include any additional properties that you want in your ApplicationIdentity class definition. In the example code below I have added a string for the email address.
using Microsoft.AspNet.Identity.EntityFramework;
namespace SimpleSPA.Models {
public class ApplicationUser: IdentityUser
{
public string Email { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext():base("DefaultConnection")
{
}
}
}
Use the solution Search and Replace to replace all references to "IdentityUser" with your new ApplicationUser.
Update the Startup static constructor in Startup.Auth.cs so that the UserManagerFactory initialisation includes your new ApplicationDbContext as below.
UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
Rebuild the solution, check it builds OK.
Enable Entity Framework Code First migrations using the "Enable-Migrations" command in the Package Manager (PM) Console.
Add the initial migration using the PM command "Add-Migration Initial".
Initialise the database using the PM command "Update-Database".
Following this if you connect to the generated database you should see that the AspNetUsers table includes columns for your additional ApplicationUser properties. I haven't gone much further yet but I would expect that I will be able to access my new properties by using ApplicationUser instead the base IdentityUser.

Resources