Merge MyDbContext with IdentityDbContext

identitydbcontext vs dbcontext
identitydbcontext example
scaffold identitydbcontext
identitydbcontext class library
add asp net identity to existing database
applicationuser : identityuser
asp net identity custom user table
asp.net core add identity to existing project

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

Additional information: One or more validation errors were detected during model generation:

Update: I found the solution.

I had to remove this naming convention:

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

And migrate the ef cf model to db, to rename my tables with the nameing conventions of asp.net identity. It is working now!

  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>

Merge MyDbContext to Asp.net IdentityDbContext, If I got you correct, you are trying to use your existing database, tables and existing users with asp.net identity framework. First thing, according  1 Answer 1. IdentityDbContext is inheriting from DBContext by default. There is no need of creating a new context (in your case tbContext) - just cut and paste the ApplicationDbContext from the IdentityModels.cs and put it to your data layer.

You may get the following message if you follow the above steps but can't work out how to provide the key information. The error you may receive is:

IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. Context.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.

Create the two following classes

public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
{

    public IdentityUserLoginConfiguration()
    {
        HasKey(iul => iul.UserId);
    }

}

public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
{

    public IdentityUserRoleConfiguration()
    {
        HasKey(iur => iur.RoleId);
    }

}

In the OnModelCreating method within your Applications DbContext add the two configurations outlined above to the model:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Configurations.Add(new IdentityUserLoginConfiguration());
        modelBuilder.Configurations.Add(new IdentityUserRoleConfiguration());

    }

This should now get rid of the error methods when your model is being created. It did for me.

How to merge IdentityDbContext and MyDbContext that aspnet , Hey guys. I am using aspnet-codegenerator cli to generate identity and aspnet-​codegenerator controller like this: dotnet aspnet-codegenerator  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.

It's worth noting that if you merge the DBContexts you are tying an authentication approach (ASP's Identity in this case) to the data access implementation (EF). From a code design point of view that could be seen as mixing your concerns and a violation of Single Responsibility Principle.

That's probably fine in the majority of cases, but if you want to reuse your data layer in other non-web applications (e.g. for a desktop or server app) this will present an issue because IdentityDbContext lives in the Microsoft.AspNet.Identity.EntityFramework namespace and your desktop or server apps are unlikely to be using AspNet Identity as their authentication mechanism.

We were in that situation and ended up keeping ASP's second DB Context, which stayed in the web project. We then cross-loaded some of the data about the user (first name, last name, etc.) into the Identity's claims object when the user signed in.

Merge MyDbContext to Asp.net IdentityDbContext, I saw a lot of examples online but none that I could use from top to bottom about merging my own DbContext with Asp.net IdentityDbContext. Can someone  Stack Overflow Public questions Merging ASP.Net Identity DbContext with my DbContext Possible duplicate of Merge MyDbContext with IdentityDbContext – Arvand

This may be an old thread, but this article was very helpful in demonstrating how to get the solution to the above question working: http://blogs.msdn.com/b/webdev/archive/2014/03/20/test-announcing-rtm-of-asp-net-identity-2-0-0.aspx

I did end having to include

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);
     //....
}

because without it, I would get the following error:

EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType. EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType. EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined. EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.

If I add these configurations as mentioned above:

public class IdentityUserLoginConfiguration : EntityTypeConfiguration<IdentityUserLogin>
{
    public IdentityUserLoginConfiguration()
    {
        HasKey(iul => iul.UserId);
    }
}

public class IdentityUserRoleConfiguration : EntityTypeConfiguration<IdentityUserRole>
{
    public IdentityUserRoleConfiguration()
    {
        HasKey(iur => iur.RoleId);
    }
}

it would create an additional foreign key called Application_User.

How to merge Identity dbcontext with application context?, _userManager is causing the issue here. It's assuming because of change tracking and the nature of your ForeignKeys that you are trying to  Fusionner MyDbContext avec IdentityDbContext j'ai un MyDbContext dans un projet de bibliothèque de classe de couches de données séparées. Et j'ai un ASP.NET projet MVC 5 avec un contexte Identitydb par défaut.

1) After you inherit the context from IdentityDbContext errors related to primary keys on the Identity tables (AspNetUsers etc) should disappear.

2) Your ApplicationUser extension of IdentityUser is missing navigation properties that are interpreted as foreign keys by the Entity Framework (these are also very useful for navigation from your code).

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; }

    //*** Add the following for each table that relates to ApplicationUser (here 1-to-many)
    public virtual IList<Case> Cases { get; set; } //Navigation property
    //*** and inside the case class you should have 
    //*** both a public ApplicationUser ApplicationUser {get;set;}
    //*** and a public string ApplicationUserId {get;set;} (string because they use GUID not int)
}

3) I read in many places that when overiding OnModelCreating, you have to call the base method. It seems that sometimes you can do without it.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         base.OnModelCreating(modelBuilder);
         //....
    }

Merge IdentityDbContext and DbContext ASP.NET MVC, I would like to only have one DbContext in my ASP.NET MVC project. How should I merge the default IdentityDbContext with my own code first DbContext? Merge MyDbContext with IdentityDbContext" To answer to all of these questions we need to understand that IdentityDbContext is just a class inherited from DbContext. Let's take a look at IdentityDbContext source :

Entity Framework Core 3.1 merge IdentityDbContext with , Entity Framework Core 3.1 merge IdentityDbContext with myDbContext I want to merge default identity DbContext with other tables (my own DbContext ); I 

[SOLVED], Based on the source code if we want to merge IdentityDbContext with our DbContext we have two options: First Option: Create a DbContext 

https://social.msdn.microsoft.com/Forums/expressio, Если я вас правильно, вы пытаетесь использовать существующие базы данных, таблицы и существующих пользователей базы личных данных asp.​net.

Comments
  • What does merge mean in this context?
  • I second this question. The new Identity RTM seems to make referencing to User complicated.
  • 'Merge' means I want just one Context in the DAL project not two independent contexts in two projects, but using the same database.
  • Hi Martonx, I am facing the same problem now. Wondering how did you create your dbContext (CrmContext)? Is it created by edmx?
  • Hi Xavier, I'm using Code First, I don't have edmx.
  • I tried this, and it seemed to work, but when I tried to make EF CF Migration, the migration failed because of missing foreign keys.
  • I updated my initial post. So everything build fine, and in runtime, I get that error in my ReposytoryBasa class.
  • So where the steps suggested helpful in achieving the questioned goal?
  • I already known these steps, but I will sign your Answer as Answer, because it is good to see these steps. I hope this topik will help everybody to solve this issue.
  • if I inherit MyDbContext from IdentityDbContext, there is no SaveChanges method
  • Hi, what is this HasKey? I got Error: The name 'HasKey' does not exist in the current context
  • Check that you have the correct imports. You obviously don't have the correct references. Are you sure you are referencing EntityFramework and it's the correct namespace import at the top of your class?