mmcc88
mmcc88

Reputation: 176

ASP.NET MVC Core: Error occurs after adding IdentityUser

I'm learning to build a ASP.NET MVC Core web application. Everything works fine until I start to add Identity to it.

Registered User can create many Jobs. I use the ApplicationUser.cs that comes with the project for the User. I created another DbContext for all others entities.

ApplicationUser.cs in Model:

public class ApplicationUser : IdentityUser
{
    // CUSTOM PROPERTIES
    public string Name { get; set; }
    public ICollection<Job> Jobs { get; set; }
}

Job.cs in Model:

public class Job 
{
    public int ID { get; set; }
    public string Title { get; set; }

    // contains other properties

    public string ApplicationUserID { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}

ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

When I add these 2 lines in Job.cs, the error pops up.

    public string ApplicationUserID { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

Error ==>>

Unhandled Exception: System.Exception: Could not resolve a service of type 'MyProject.Data.JobDbContext' for the parameter 'context' of method 'Configure' on type 'MyProject.Startup'. ---> System.InvalidOperationException: The entity type 'IdentityUserLogin' requires a primary key to be defined.

I know that there are some threads discussing about the same error, but those answer can't really help.

Upvotes: 0

Views: 1104

Answers (1)

Dmitry
Dmitry

Reputation: 16825

Your problem is two different contexts.

JobDbContext contains Job, which refers to ApplicationUser which is NOT in this context, but added by EF automatically because you linked to it. And this ApplicationUser (it's parent IdentityUser) contains collection of logins (IdentityUserLogin) which is not part of this context too, but auto-added by EF, and so on... All this classes are configured in OnModelCreating of IdentityDbContext and NOT configured in JobDbContext that's why you see this error - you have no description keys/indexes/references of this classes in JobDbContext.

You should either combine two DbContext into one, or remove public virtual ApplicationUser ApplicationUser { get; set; } from Job class and manage related object manually (ensure referential integrity, do lazy loading etc).

Upvotes: 2

Related Questions