使用 ASP.NET 标识的 WinForms 应用程序中的 ModelValidationException:EntityType 没有定义键

ModelValidationException in WinForms app using ASP.NET Identity: EntityType has no key defined

我正在使用 ASP.NET MVC5 和 ASP.NET 用户身份验证开发 Web 应用程序。我的数据库是使用 EF Code First 构建的。我用一些属性扩展了 ApplicationUser:

public class ApplicationUser : IdentityUser
{
    [StringLength(80)]
    [Display(Name = "FullName", ResourceType = typeof(Resources.Resources))]
    public string FullName { get; set; }

    // More properties

    public virtual ICollection<Installation> Installations { 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;
    }
}

这是安装class(如您所见,已定义 Key 属性):

public class Installation
{
    [Key]
    [Required]
    [StringLength(15)]
    [Display(Name = "Imei", ResourceType = typeof(Resources.Resources))]
    public string Imei { get; set; }

    [Display(Name = "Name", ResourceType = typeof(Resources.Resources))]
    [StringLength(50)]
    [Required]
    public string Name { get; set; }

    // More properties

    public virtual ICollection<ApplicationUser> Users { get; set; }
}

这些 class 是在 class 库中定义的。该库在 Web 应用程序项目和 Windows Forms 项目中被引用。

以下 this answer 我使用这两行使用用户名和密码登录:

var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
ApplicationUser user = await userManager.FindAsync(this.tbUser.Text, this.tbPassword.Text);

Web 应用程序运行良好,我可以根据登录用户的角色创建、编辑、删除和查看用户和安装的详细信息。但是我在 Windows 中获取用户时遇到问题表格申请。我在 user.Manager.FindAsync() 行得到这个异常:

System.Data.Entity.ModelConfiguration.ModelValidationException was unhandled by user code
  HResult=-2146233088
  Message=One or more validation errors were detected during model generation:

MyProjectWeb.Models.Installation: : EntityType 'Installation' has no key defined. Define the key for this EntityType.
Installations: EntityType: EntitySet 'Installations' is based on type 'Installation' that has no keys defined.

  Source=EntityFramework
  StackTrace:
       at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate()
       at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
       at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
       at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
       at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
       at System.Data.Entity.Internal.InternalContext.Initialize()
       at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       at System.Data.Entity.Internal.Linq.InternalSet`1.Include(String path)
       at System.Data.Entity.Infrastructure.DbQuery`1.Include(String path)
       at System.Data.Entity.QueryableExtensions.Include[T](IQueryable`1 source, String path)
       at System.Data.Entity.QueryableExtensions.Include[T,TProperty](IQueryable`1 source, Expression`1 path)
       at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.GetUserAggregateAsync(Expression`1 filter)
       at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.FindByNameAsync(String userName)
       at Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync(String userName)
       at Microsoft.AspNet.Identity.UserManager`2.<FindAsync>d__12.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
       at MyProjectForm.FormConectar.<Login>d__2.MoveNext() in f:\...\Solution\MyProjectForm\FormConectar.cs:line 158
  InnerException: 

没有 InnerException 信息。我尝试 获取更多信息,但这些是不同的异常,因此它永远不会进入 catch 块。

最奇怪的是,之前它确实运行良好,但我不知道我做了什么,现在我得到这个错误。

我已经解决了覆盖 ApplicationDbContext 的 OnModelCreating 方法的问题 class 指定键:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<Installation>().HasKey(c => c.Imei);
     base.OnModelCreating(modelBuilder);
}