Asp.net

不支持每種類型的多個對象集。對象集“ApplicationUsers”和“Users”都可以包含 ApplicationUser 類型的實例

  • August 2, 2018

我陷入了一個奇怪的問題。

我正在學習 MVC 5,幾乎所有內容都是由內置模板創建的。我只添加了一個班級歷史

public class History
{
   [Key]
   public DateTime Date { get; set; }

   public virtual ApplicationUser User { get; set; }

   public string ItemName { get; set; }

}

在內置的 ApplicationUser 內部:

 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
           return userIdentity;
       }

       public virtual ICollection<History> Histories { get; set; }
   }

這是錯誤消息:

Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'MyOnlineShopping.Models.ApplicationUser'.

   Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

   Exception Details: System.InvalidOperationException: Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'MyOnlineShopping.Models.ApplicationUser'.

   Source Error: 


   Line 124:            {
   Line 125:                var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
   Line 126:                IdentityResult result = await UserManager.CreateAsync(user, model.Password);
   Line 127:                if (result.Succeeded)
   Line 128:                {
Source File: f:\Workplace\MyOnlineShopping\MyOnlineShopping\Controllers\AccountController.cs    Line: 126 

以上只是一種解決方法,圍繞 SO 有很多相同問題的答案。

這裡

這裡

這裡

查看 IdentityModel.cs 裡面,你會發現

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

在這種情況下,VS 有時會添加 DbSet<ApplicationUser> ApplicationUsers

這是重複的

IdentityDbContext 類的內部是一個 DbSet 使用者,當您從 IdentityContext 子類化時,繼承將該行轉換為DbSet<ApplicationUser> User.

修復?DbSet<ApplicationUser> User從_ public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

當您的ApplicationDbContext班級更改時會發生此錯誤。只需在您的模型文件夾中執行此操作,然後去IdentityModels.cs上課並刪除最後一行

public System.Data.Entity.DbSet < Project.Models.ApplicationUserProject.Models.ApplicationUser> ApplicationUsers { get; set; }

這條線是腳手架自動生成的。

引用自:https://stackoverflow.com/questions/23935573