在 MVC 5 中使用 Microsoft.AspNet.Identity 脚手架

Scaffolding with Microsoft.AspNet.Identity in MVC 5

我正在尝试使用脚手架和 Microsoft.AspNet.Identity 创建一个新的控制器,但我收到一条错误消息 "IdentityUserLogin" has no key defined.

我正在尝试在客户 table 和 Microsoft.AspNet.Identity 用户的 table 之间建立关系。

我用来建立关系的字段是 UserCreatedUserModifiedUserAssigned

型号是:

[Table("Clients")]
public partial class Client
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Display(Name = "Criado em")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-M-yyyy HH:mm}")]
    public DateTime DateCreated { get; set; }

    [Display(Name = "Alterado em")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-M-yyyy HH:mm}")]
    public DateTime DateModified { get; set; }

    [MaxLength(128)]
    public virtual string UserCreated_Id { get; set; }

    [ForeignKey("UserCreated_Id")]
    public virtual ApplicationUser UserCreated { get; set; }

    [MaxLength(128)]
    public virtual string UserModified_Id { get; set; }

    [ForeignKey("UserModified_Id")]
    public virtual ApplicationUser UserModified { get; set; }

    [MaxLength(128)]
    public virtual string UserAssigned_Id { get; set; }

    [ForeignKey("UserAssigned_Id")]
    public virtual ApplicationUser UserAssigned { get; set; }

    [Required]
    [MaxLength(256)]
    [Display(Name = "Nome")]
    public string Name { get; set; }

    [Display(Name = "Morada")]
    [MaxLength(512)]
    public string Address { get; set; }

    public int PostalCode { get; set; }
    public int PostalCodeExtension { get; set; }

    [MaxLength(256)]
    public string PostalCodeCity { get; set; }

    [Display(Name = "Telefone")]
    [MaxLength(50)]
    public string Telephone { get; set; }

    [Display(Name = "Fax")]
    [MaxLength(50)]
    public string Fax { get; set; }

    [Display(Name = "Email")]
    [MaxLength(256)]
    public string Email { get; set; }

    [Display(Name = "Contribuinte")]
    [MaxLength(50)]
    public string VAT { get; set; }
}

可能是因为你是这样定义的ApplicationUser。我使用以下实现并且它完美运行 -

public class ApplicationUserLogin : IdentityUserLogin<int>
{
}

public class ApplicationUserRole : IdentityUserRole<int>
{

}

public class ApplicationUserClaim : IdentityUserClaim<int>
{
}

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{

}

然后像这样使用它 -

public class DomainEntity : .....
{
    [Key]
    public virtual int Id { get; set; }
    public virtual ApplicationUser CreatedBy { get; set; }

    public virtual ApplicationUser LastUpdatedBy { get; set; }

}

EDIT:用户管理器需要第二个参数,密钥类型。所以改变它 - 这个

 UserManager<ApplicationUser, int>

及其他 -

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>