Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two IdentityDbContext in the same database

I have a web api. I want it to have two types of users. They are completely unrelated.

How can I manage authentication of they both?

I don't want to have them in the same table and manage the type of them as Roles, because they are different entities. One kind of user is used by humans and the other one is used by services. They have different classes and attributes. I would like to have something like two IdentityDbContext but I want to maintain all in the same database. Do you think is possible?

like image 549
Ricardo Polo Jaramillo Avatar asked Jan 11 '23 03:01

Ricardo Polo Jaramillo


1 Answers

I'm not sure if that is a good practice, but you could use different schemas, like:

[dbo].UserProfile and [webapi].UserProfile

As far as I understood you are using ASP.NET MVC and using the default IdentityDbContext that comes with the Empty Project.

It uses a CodeFirst approach that creates the tables on your database. You just need to create the other one you need and configure it to use the different schema.

EDIT - Example

Notice [Table("UserProfile", Schema = "dbo")] and [Table("UserProfile", Schema = "webapi")]

This way EF will notice that you're trying to fetch data from different tables.

[Table("UserProfile", Schema = "dbo")]
public class UserProfile
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

[Table("UserProfile", Schema = "webapi")]
public class UserProfileWebApi
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

If you want to go further, you can create an interface for both classes. But again, I don't believe this is a good practice, you should just create a table with a different name to avoid confusion.

like image 105
Pedro Matos Avatar answered Jan 12 '23 17:01

Pedro Matos