Home > Blockchain >  Different DbContexts for different user roles
Different DbContexts for different user roles

Time:12-09

So. Сan you explain to me whether the correct approach would be to have different DBContext for different types of users.

For example: We have ApiController with 2 methods:

[HttpGet, Route("admin"), Authorize(RoleType.Admin)]
public Task<...> Get(... adminRequest)
{
    var query = mapper<AdminGetCommand>(adminRequest);
    return mediatr.Send(query);
}

[HttpGet, Route(""), Authorize(RoleType.User)]
public Task<...> Get(... userRequest)
{
    var query = mapper<UserGetCommand>(userRequest);
    return mediatr.Send(query);
}

after that every command depends on different Service/DbContext witch has different configuration. For example:

//filter for users
...
protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.ApplyGlobalFilters<IDeletedUtcDateTime>(e => !e.DeletedUtcDateTime.HasValue);

}
...

//filter for admin 
...
protected override void OnModelCreating(ModelBuilder builder)
{
    ...
    base.OnModelCreating(builder);
    ...
}
...

I feel like I'm missing something or better solution exists here

CodePudding user response:

Сan you explain to me whether the correct approach would be to have different DBContext for different types of users.

It's a reasonable approach if you want a different set of global query filters (or other mapping or behavior changes) for the users. You can simply derive UserDbContext from AdminDbContext or derive both from a base DbContext, and register them separately in DI.

  • Related