ASP.NET MVC Core: Error occurs after adding IdentityUser

拜拜、爱过 提交于 2019-12-12 04:32:06

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/41377293/asp-net-mvc-core-error-occurs-after-adding-identityuser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!