【问题标题】:How AspNet Identity with my modelAspNet 如何识别我的模型
【发布时间】:2014-01-07 19:18:04
【问题描述】:

我正在尝试在the External Authentication Services (C#) 上完成本教程。我需要一些初步的解释才能继续前进。查看附带 MVC5 的默认模板,我看到了:

// You can add profile data for the user ...
public class ApplicationUser : IdentityUser
{
    public string HomeTown { get; set; }
    public DateTime? BirthDate { get; set; }
}

如果我想将其称为 User 而不是 ApplicationUser 怎么办?也许我想添加一个导航属性,以便与其他模型建立关系?此外,当我查看表格时,名称是 AspNetUsers 而不是 ApplicationUser。最后,如果我想使用自己的上下文怎么办?

感谢您的帮助。

【问题讨论】:

    标签: asp.net-mvc asp.net-identity


    【解决方案1】:

    1)如果我想称它为 User 而不是 ApplicationUser 怎么办?

    您可以更改为您想要的任何名称,只需确保将 ApplicationUser 替换为该名称即可。

    2)也许我想添加一个导航属性,这样我就可以建立 与我的其他模特的关系?

    如果你有一个类调用Address,你想添加addressId作为外键,见下:

     public class Address
    {
        public int Id { get; set; }
        public string Street { get; set; }
    }
    
    public class User : IdentityUser
    {
        public string HomeTown { get; set; }
        public DateTime? BirthDate { get; set; }
        public int AddressId { get; set; }
        [ForeignKey("AddressId")]
        public virtual Address Address { get; set; }
    }
    
    public class ApplicationDbContext : IdentityDbContext<User>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
        public DbSet<Address> Addresses { get; set; }
    }
    

    3)另外,当我查看表格时,名称是 AspNetUsers 而不是 应用程序用户。

    ASP.NET 身份继承自 ASP.NET 会员系统。当您注册新用户时 使用默认模板,AspNetUsers 和 AspNetUserRoles 等。这些表是默认创建的。 您可以通过修改 IdentityModel.cs 来修改这些表名。更多详情请查看以下链接:

    How can I change the table names when using Visual Studio 2013 ASP.NET Identity?

    4)如果我想使用自己的上下文怎么办?

    您可以创建自己的 DBContex,MVC 5 允许您拥有多个 DBContext,例如 ApplicationDbContext 和 DataDbContext(custom DbContext)。 ApplicationDbContext 通常包含 ASP.NET Membership 数据表。 DataDbContext 通常包含与用户无关的数据表。

    public class Blog
    {
        public int BlogId { get; set; }
        public int Title { get; set; }
    }
    
    public class MyDbContext : DbContext
    {
        public MyDbContext() 
            : base("DefaultConnection")
        {
    
        }
        public DbSet<Blog> Blogs { get; set; }
    }
    

    注意:您可能需要使用 EF 迁移,请在此处查看详细信息:

    ASP.Net Identity customizing UserProfile

    【讨论】:

    • 默认数据库和表在哪里创建?
    • @Lin,非常感谢您的回答。另一个快速的问题 - 如果我想在我自己的模型中有一个字段来引用 ApplicationUser。我该如何做到这一点?
    猜你喜欢
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 2012-06-20
    相关资源
    最近更新 更多