2

I am building a single page application, so I used the visual studio default template. When It was on development I had 2 databases Entityframework.mdf and Identity.mdf, because thats what the default configuration does, but now I need relation ship with the users and I can't reach them easly because they are in another database.

in an MVC template you can easly do it like this:

public class ApplicationUser: IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
    public DbSet<CustomTableItem> CustomTable{ get; set; } 
    //You can add more tables
}

when you use the single page application it configures the user management in a way I don't understand.

UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());

then from this article

This code uses the default constructor for the UserStore class, which will create a new instance of an IdentityDbContext object since an object isn’t supplied. If you want to use your own IdentityDbContext derived class, like the MVC 5 project does, you can modify the above initialization code and pass in your own context.

it says I can modify it but it does not show how :(, and I have tried but I can’t make it work. This is what I am trying to do

UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

what am I missig?

bto.rdz
  • 6,636
  • 4
  • 35
  • 52

1 Answers1

3

If you use default constructor (with not parameters) for UserStore class, this happens:

public UserStore()
{
  this..ctor((DbContext) new IdentityDbContext());
  this.DisposeContext = true;
}

Identity framework creates it's own database context for you with default connection string and no relation to your own models or DbContext.

What Scott says in his article is that UserStore has a constructor defined like this:

public UserStore(DbContext context)
{
  base..ctor(context);
}

In other words you can supply your DbContext as a parameter into the constructor of UserStore:

UserManagerFactory = () => new UserManager<ApplicationUser>(
    new UserStore<ApplicationUser>(new ApplicationDbContext()))

Where ApplicationDbContext is defined as you describe in the question.

You'll need to create a migration on ApplicationDbContext that will create Identity tables in Entityframework.mdf. Then you'll have to move data from Identity.mdf into your main database. Connect to both datbases and run something like this:

insert into EntityFramework.dbo.IdenetityUsers
select * from Identity.dbo.IdentityUsers

However, I've only done data migration from one DB to another one within single SQL Server instance, not between LocalDbs (I presume you used these). So this method might not work and you'll have to export data from Identity.mdf into csv files and import them into EntityFramework.mdf

trailmax
  • 34,305
  • 22
  • 140
  • 234