ASP.NET Identity - 不支持每种类型的多个对象集。

59

我在我的应用程序中使用ASP.NET身份验证时遇到了错误。

不支持每个类型的多个对象集。 对象集'Identity Users'和'Users'都可以包含类型'Recommendation Platform.Models.ApplicationUser'的实例。

我在StackOverflow上看到了一些关于此错误的问题。所有问题都指向相同类型的两个DbSet对象。但是在我的DbContext中,没有相同类型的DbSets。在登录期间的FindAsync()方法中抛出异常。

if (ModelState.IsValid)
    var user = await UserManager.FindAsync(model.UserName, model.Password);
    if (user != null && user.IsConfirmed)
    {

问题是我没有两个相同类型的DbSets。我的上下文看起来像这样:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    public System.Data.Entity.DbSet<RecommendationPlatform.Models.ApplicationUser> IdentityUsers { get; set; }

}

public class RecContext : DbContext
{
    public RecContext()
        : base("RecConnection")
    {
        Database.SetInitializer<RecContext>(new DropCreateDatabaseIfModelChanges<RecContext>());
    }

    public DbSet<Recommendation> Recommendations { get; set; }
    public DbSet<Geolocation> Geolocations { get; set; }
    public DbSet<Faq> Faqs { get; set; }
    public DbSet<IndexText> IndexTexts { get; set; }
}

可能是与内置的 ASP.NET Identity 功能相关的问题导致的?无论如何,“Users”类型是什么?我在我的应用程序中没有它...

什么可能会导致这个问题?也许与内置的 ASP.NET Identity 功能有关?不管怎样,“Users” 类型是什么?我在我的应用程序中没有它...

5个回答

110

您确实有两个相同类型的DbSet

IdentityDbContext<T>本身包含声明为Users属性的:

public DbSet<T> Users { get; set; }
你正在类中声明第二个。

11
请查看IdentityModel.cs文件,您会发现下面的代码: public class ApplicationDbContext : IdentityDbContext<ApplicationUser>在这个上下文(context)中,Visual Studio有时会添加以下代码: DbSet<ApplicationUser> ApplicationUsers - Vasil Valchev
@VasilValchev 当你继承自IdentityUser类时,它包含了Users DbSet。 - AminM
我也遇到了同样的错误,但我从未在IdentityModel.cs中添加过这行代码。它是如何神奇地出现并开始抛出错误的呢?我甚至将我的更改上传到了git。这行代码是如何神奇地出现的呢?请指导我。附言:注释掉那行代码可以解决问题。 - Unbreakable
你怎么解决这个问题呢?仅仅删除属性意味着它将无法再被访问。 - Martin Vaughan

70

请审查文件 "ApplicationDbContext.cs",移除由scaffold自动生成的最后一行,应该像这样:

public System.Data.Entity.DbSet<Manager.Models.ApplicationUser> IdentityUsers { get; set; }

谢谢,现在我知道罪魁祸首是新控制器向导刚刚创建的脚手架。 - VivekDev
不错!我从来没有使用过脚手架,但在使用它构建控制器后,一切都出了问题!好提示,兄弟! - Leandro De Mello Fagundes
仅仅删除该属性意味着它将无法再被访问。 - Martin Vaughan

11
这个问题可能是由于使用脚手架创建视图引起的。你可能做了这样的事情:视图 > 添加 > 新建脚手架项... > MVC 5 视图 > [模型类:ApplicationUser]。{{code}}

Add View Screenshot

脚手架向导在您的ApplicationDbContext类中添加了一行新代码。

public System.Data.Entity.DbSet<RecommendationPlatform.Models.ApplicationUser> IdentityUsers { get; set; }

现在你有两个相同类型的DbSet属性,这不仅会导致在FindAsync()方法中抛出异常,而且当你尝试使用Code-First迁移时也会抛出异常。

Exception when using code-first migrations

在使用脚手架时一定要非常小心,最好不要使用它。


1
这正是发生在我身上的事情!注意:如果您使用脚手架生成控制器,则需要在控制器中将“ApplicationUser”更改为“User”。 - SendETHToThisAddress

1
每当我遇到这个问题时,我总是会仔细检查DbSet。-特别是如果您在Visual Studio中使用其他语言。
对于我们在VS上使用其他语言的人来说,一定要仔细检查,因为程序不会使用完全相同的名称创建控制器或模型。也许这应该成为一个主题...或者已经有一个主题了,我可能错过了它。

0

像下面这样注释身份模型类生成的新Dbset

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接