How AspNet Identity with my model

2019-02-05 03:06发布

I'm trying to go through this tutorial on the External Authentication Services (C#). I need some initial explanations to go forward. Looking inside the default template that ships MVC5, I see this:

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

What if I want to call it User instead of ApplicationUser? Maybe I want to add a navigation properties so I can establish relationship with my other models? Also when I look at the table, the name is AspNetUsers instead of ApplicationUser. Finally, What if I want to use my own context?

Thanks for helping.

1条回答
够拽才男人
2楼-- · 2019-02-05 03:25

1)What if I want to call it User instead of ApplicationUser?

You can change to any names you want, just make sure to replace ApplicationUser with the name.

2)Maybe I want to add a navigation properties so I can establish relationship with my other models?

If you have a class call Address, you want to add addressId as a foreign key, see below:

 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)Also when I look at the table, the name is AspNetUsers instead of ApplicationUser.

ASP.NET Identity is inherited from the The ASP.NET membership system. When you register a new user using the default template, AspNetUsers and AspNetUserRoles etc.. these tables are created by default. You can modify these table name by modifying the IdentityModel.cs. For more detail take a look at the following link:

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

4)What if I want to use my own context?

You can create your own DBContex, MVC 5 allow you to have mutiple DBContext, such as ApplicationDbContext and DataDbContext(custom DbContext). ApplicationDbContext usually contains ASP.NET Membership data table. DataDbContext usually contains data tables unrelated to users.

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

Note: You may need to use EF Migrations, see details here :

ASP.Net Identity customizing UserProfile

查看更多
登录 后发表回答