C# 从ASP.Net MVC 5标识添加外键时出错?

C# 从ASP.Net MVC 5标识添加外键时出错?,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我有一个客户模型: public class Customer { [Key, ForeignKey("ApplicationUser")] public string UserId { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } public string Title { get; set; } } 我想这就是我的IdentityModel.cs的样子: p

我有一个客户模型:

public class Customer
{
    [Key, ForeignKey("ApplicationUser")]
    public string UserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

    public string Title { get; set; }
}
我想这就是我的IdentityModel.cs的样子:

public class ApplicationUser : IdentityUser
{
    public virtual Customer Customer { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}
公共类应用程序用户:IdentityUser
{
公共虚拟客户客户{get;set;}
公共异步任务GenerateUserIdentityAsync(用户管理器

出什么问题了?除了ApplicationUser:IdentityUser类和Customer类之外,我没有更改任何内容


我对这一点非常陌生,因此我希望得到非常详细的说明:)

尽管您没有发布IdentityUserLogin、IdentityUserRole等。我可以想象您没有为这些类定义主键。实体框架需要每个和。 您可以按照约定命名主键属性Id或ClassNameId,或者使用数据注释,尤其是键

更新 根本的问题与外键无关,而是缺少主键

首先,不应将属性同时定义为Key和ForeignKey。 从UserId中删除Key属性,只保留ForeignKey。 接下来定义一个Id属性,如下所示:

    public int Id { get; set; }
实体框架足够智能,可以将其识别为主键。
在所有实体中执行此操作,更新数据库,就可以开始了。

您可以显示上下文类代码吗?可能需要添加类似于
modelBuilder.Conventions.Remove()的内容
在那里。我想你指的是ApplicationDbContext类?我没有对它做任何修改。但我还是添加了它。@TetsuyaYamamotoYep,我至少想先看看你的
ApplicationDbContext
&其他相关的上下文类。由于它缺少标识表的PK定义,所以配置错误。我将它添加到了Id中entity Model.cs.刚刚刷新。我只更改了ApplicationUser类。其他我没有更改。@Tetsuyayamamoto此时,请尝试添加
base.OnModelCreating(modelBuilder);
在ModelCreating(DbModelBuilder modelBuilder)中被重写的
内部
method。让我知道这是否解决了问题。我该怎么做?我仍然不熟悉MVC和ASP.net
    public int Id { get; set; }