Search code examples
asp.net-mvcasp.net-identity

Merge MyDbContext with IdentityDbContext


I have a MyDbContext in a separated Data Accass Layer class library project. And I have an ASP.NET MVC 5 project with a default IdentityDbContext. The two context use the same database, and I want to use AspNetUsers table to foreign key for some my tables. So I would like to merge the two Context, and I want to use ASP.NET Identity too.

How can I do this?

Please advice,

This is my Context after merge:

public class CrmContext : IdentityDbContext<CrmContext.ApplicationUser> //DbContext
{
    public class ApplicationUser : IdentityUser
    {
        public Int16 Area { get; set; }
        public bool Holiday { get; set; }
        public bool CanBePublic { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    public CrmContext()
        : base("DefaultConnection")
    {
        
    }
    
    public DbSet<Case> Case { get; set; }
    public DbSet<CaseLog> CaseLog { get; set; }
    public DbSet<Comment> Comment { get; set; }
    public DbSet<Parameter> Parameter { get; set; }
    public DbSet<Sign> Sign { get; set; }
    public DbSet<Template> Template { get; set; }
    public DbSet<Read> Read { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

Here is my RepositoryBase class:

    public class RepositoryBase<TContext, TEntity> : IRepositoryBaseAsync<TEntity>, IDisposable
        where TContext : IdentityDbContext<CrmContext.ApplicationUser> //DbContext
        where TEntity : class
    {
        private readonly TContext _context;
        private readonly IObjectSet<TEntity> _objectSet;

        protected TContext Context
        {
            get { return _context; }
        }

        public RepositoryBase(TContext context)
        {
            if (context != null)
            {
                _context = context;
                //Here it is the error:
                _objectSet = (_context as IObjectContextAdapter).ObjectContext.CreateObjectSet<TEntity>();
             }
             else
             {
                 throw new NullReferenceException("Context cannot be null");
             }
         }
     }

An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code.


Solution

    1. Move the ApplicationUser definition to your DAL.
    2. Inherit your MyDbContext from IdentityDbContext<ApplicationUser> or IdentityDbContext
    3. OnModelCreating - Provide the foreign key info.
    4. Pass MyDbContext while creating the UserManager<ApplicationUser>