我正在尝试使用调查MVC Web应用程序的Microsoft Identity 2扩展和存储用户首选项。
目前,我只想存储用户的仪表板问题类型类型视图(1至5星,或0到10 NPS系统(。
我创建了一个具有以下属性的表Aspnetuserpreferences:
Id (int)
UserId (nvarchar(128))
DashboardQuestionType (int)
和模型:
[Table("AspNetUserPreferences")]
public class UserPreference
{
[Key]
public int Id { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
public QuestionType DashboardQuestionType { get; set; }
}
public enum QuestionType
{
[Display(Name = "Enum_Type_Numeric_1_to_5_Display", ResourceType = typeof(ResQuestion))]
Numeric1to5 = 1,
[Display(Name = "Enum_Type_Numeric_0_to_10_Display", ResourceType = typeof(ResQuestion))]
Numeric0to10 = 2,
[Display(Name = "Enum_Type_Text_Display", ResourceType = typeof(ResQuestion))]
Text = 3,
[Display(Name = "Enum_Type_Yes_No_Display", ResourceType = typeof(ResQuestion))]
YesNo = 6
}
上下文:
public class ApplicationUser : IdentityUser
{
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
userIdentity.AddClaim(new Claim("Company_Id", this.Company_Id.ToString()));
userIdentity.AddClaim(new Claim("PTLocationDistrict", this.PTLocationDistrict.ToString()));
userIdentity.AddClaim(new Claim("Location_Id", this.Location_Id.ToString()));
return userIdentity;
}
// Additional properties for the Application User
public string FullName { get; set; }
public virtual int Company_Id { get; set; }
[ForeignKey("Company_Id")]
public virtual Company Company { get; set; }
public PTLocationDistrict PTLocationDistrict { get; set; }
public virtual int? Location_Id { get; set; }
[ForeignKey("Location_Id")]
public virtual Location Location { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("SurveyDB", throwIfV1Schema: false) { }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
当我尝试运行应用程序时,它根本不会返回数据库中的任何数据,并生成错误:
EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
Microsoft Identity实现使用IdentityUser,IdentityUserLogin等,它们映射到表Aspnetusers,Aspnetuserlogins等,自来通常可以很好地奏效,因为它们在场景后面处理了默认上下文。当添加与身份表相关的新表(例如UserId FK NVarchar(128(,映射器不知道此表primary(。应用程序dbContext代码中仅有构造函数初始化,因此在那里添加dbset&lt;> aspnetuserPreference可能足以在其中添加dbset&lt;需要在模型文件夹中定义的aspnetuserpreference.cs类,以及上下文类中的以下其他代码(合适的修改以适合您的类(。
public virtual DBSet<AspNetUserPreference> AspNetUserPreferences { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AspNetUserPreferences>(entity =>
{
entity.HasIndex(e => e.NormalizedName)
.HasName("RoleNameIndex")
.IsUnique()
.HasFilter("([NormalizedName] IS NOT NULL)");
entity.Property(e => e.Id).ValueGeneratedNever();
});