简体   繁体   中英

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.

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; } public virtual ApplicationUser ApplicationUser { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } from Job class and manage related object manually (ensure referential integrity, do lazy loading etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM