【问题标题】:One-to-many MVC Individual User Accounts一对多 MVC 个人用户帐户
【发布时间】:2018-05-03 03:01:20
【问题描述】:

我正在使用带有个人用户帐户模板的 asp.net mvc,我尝试在其中建立从用户到项目的一对多关系。

在没有个人用户帐户模板的项目中,我可以简单地执行以下操作:

public class User
{
    public int UserID { get; set; }
    public string Username { get; set; }

    public virtual ICollection<Item> Items { get; set; }

}

还有

  public class Item
{
    public int ItemID { get; set; }
    public string ItemName { get; set; }
    public int UserID { get; set; }

    public virtual User User { get; set; }
}

问题是我在个人用户帐户模板中找不到用户 (ApplicationUser) 的完整模型。所以我不知道如何将项目添加到用户并为用户生成一个控制器(在单个用户模板中)

【问题讨论】:

  • 请检查您的拼写和语法。

标签: c# asp.net-mvc


【解决方案1】:

来自 Models 文件夹中的模板,在 IdentityModels 中:

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

    // Add here ..
    public string DisplayName { get; set; }
    public virtual ICollection<Item> Items { get; set; }
}

以这种方式在ApplicationUser 模型中使用身份绑定。您也可以在此处将名称 ApplicationUser 更改为 User,前提是所有其他对 ApplicationUser 的引用也已更新。

【讨论】:

  • 谢谢,我的数据库中有外键。但是,我的 ItemController 出现错误:“不支持每种类型的多个对象集。对象集“ApplicationUsers”和“Users”都可以包含“WebProject.Models.ApplicationUser”类型的实例。”
  • 听起来你有两个“用户”实例。使用 Identity 进行身份验证,“用户”,无论它叫什么,都必须从“IdentityUser”继承。答案中给出的代码是“用户”(在这种情况下,称为 ApplicationUser)。我会尝试删除您的(可能是其他)用户类,并只使用上面的类(ApplicationUser),直到建立起来,然后,如果您愿意,将名称更改为“用户”并将其移动到您想要的位置。关键是“用户”(只有一个类,不是两个)必须从 IdentityUser 继承。
  • ...只需将您在其他 User 类中的内容(根据关系和其他字段)复制到上面的代码中,删除您的其他 User 实例,然后重试。
  • 不错。很高兴它有帮助:-)
猜你喜欢
  • 1970-01-01
  • 2012-07-11
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多