【问题标题】:Scaffolding ApplicationUser脚手架应用用户
【发布时间】:2014-12-08 17:11:40
【问题描述】:

我正在使用带有 EF 6 的 ASP.NET MVC 5 的默认模板。它将身份模型生成为

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 class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

我希望能够管理和编辑用户列表,因此我搭建了身份模型并在 ApplicationDbContext 类中添加了以下行。

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

我知道这是错误的,但我不确定如何解决。

【问题讨论】:

  • 你是新建了ApplicationUser类,还是继承自IdentityUser
  • @BrendanGreen 从上面的代码可以看出,ApplicationUser 继承自 IdentityUser。
  • 那么您是如何“搭建”ApplicationUser 的?由于您的上下文继承自 IdentityDbContext,因此您不需要在您的类中定义的 dbset。

标签: asp.net-mvc-5 entity-framework-6


【解决方案1】:

如果您想管理使用所有默认设置启用迁移时为您生成的 AspNetUsers 表,请按照以下步骤操作。

  • 首先使用带有视图的 MVC 5 控制器创建控制器,使用 外语

  • 使用以下设置添加您的控制器。 Use async controller actions 不应在此处选择/选中,因为 Users DbSet 不支持异步,除非我们将使用 UserManager。那将是一个不同的话题。

  • 转到生成的控制器并将ApplicationUsers的所有实例重命名为Users

  • 最后,您现在可以安全地删除 IdentityModel 上的 ApplicationUsers(在我的情况下,它是第 37 行)

我们需要删除我在最后一张图片中显示的第 37 行,因为当您运行 enable-migrations 时它将无法构建。由于IdentityDbContext&lt;T&gt; 本身已经包含Users 属性。因此,无需在ApplicationDbContext 类或您为此声明的任何类下添加额外的DbSet。顺便说一下,这个属性是你脚手架时自动添加的ApplicationUser

【讨论】:

    【解决方案2】:

    这些步骤让我成功搭建了 ApplicationUser:

    1. 将 ApplicationUser 名称重构为其他名称,例如 MyAppUser,
    2. 使用 EntityFramework 添加控制器,使用模型 MyappUser,这将成功搭建 MyAppUser,
    3. Scaffolding 将为 ApplicationDbContext 创建属性DbSet&lt;MyAppUser&gt; MyAppUsers,将其删除
    4. 在新创建的控制器中,将所有出现的db.MyAppUsers更改为db.Users

    那么你就可以走了,希望这会有所帮助

    【讨论】:

    • 您能否进一步详细说明原因?特别是步骤 3. 和 4.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 2020-03-03
    相关资源
    最近更新 更多