Search code examples
c#asp.netasp.net-mvc-5dbcontextasp.net-identity-2

How to move ASP.net identity to other context


Currently I have two DB Contexts, One which I created called CompetentieContext, and another used only by ASP.net's Identity framework called ApplicationDBContext.

I need to have both in the same context, but I don't know how to migrate my CompetentieContext to the ApplicationDBContext or vice-versa.

I need them in the same context because I need to link the GUID's of ASP.net users to a Table in my Database.

This is how my context class looks like:

public class CompetentieContext : DbContext 
{
    public DbSet<Werknemer> Werknemer { get; set; }
    public DbSet<Competentie> Competentie { get; set; }
    public DbSet<CompetentieWerknemer> CompetentieWerknemer { get; set; }
    public DbSet<CompetentieWerknemerDetail> CompetentieWerknemerDetail { get; set; }
    public DbSet<Tag> Tag { get; set; }
    public DbSet<TagGroupTag> TagGroupTag { get; set; }
    public DbSet<TagGroup> TagGroup { get; set; }
    public DbSet<CompetentieTag> CompetentieTag { get; set; }

}

Solution

  • First create a table called WebUsers (or something similar) in your own database. It should be something like this:

    CREATE TABLE [dbo].[WebUsers](
        [Id] [uniqueidentifier] NOT NULL,
        [SomeColumnName] [nvarchar](255) NOT NULL,
        [FkSomethingInYourOwnDb] [uniqueidentifier] NULL,
        [WebUserId] [nvarchar](128) NOT NULL,
        ...
      CONSTRAINT [PK_WebUsers] PRIMARY KEY CLUSTERED ([Id] ASC) ON [PRIMARY]
    ) ON [PRIMARY]
    

    Note the [WebUserId] column which maps to [AspNetUsers] primary key column.

    Now after updating your EF model/context (this depends on which approach you use), create an abstraction called something like IWebUserContext and it's implementation HttpWebUserContext:

    public interface IWebUserContext
    {
        string Id { get; }
    }
    
    public class HttpWebUserContext : IWebUserContext
    {
        public string Id => HttpContext.Current.User.Identity.GetUserId();
    }
    

    Next you can create your own context abstraction, let's call this ICompetentieUserContext:

    public interface ICompetentieUserContext
    {
        WebUserModel CurrentUser { get; }
    }
    

    Where WebUserModel is the EF entity we just created.

    The implementation for this abstraction is entirely up to you, since I don't know your application's architecture. But you could, for example, use Dependency Injection, to inject the IWebUserContext into ICompetentieUserContext's implementation.

    You could also inject the EF dbcontext directly into your implementation (although I'd prefer using some kind of Repository pattern), and map the current WebUserContext's Id to the one in your database.