-4

I'm looking for assistance here. I've built an application that uses .NET Core 3.1, identity, and EF Core. I've extended aspnetusers to include additional columns. My company uses stored procedures for all other db queries.

My question is how do I go about getting the currently logged-in users' information and using this information (that includes the custom extended identity) in a FromSqlRaw select statement against the database. Currently, my user is hard-coded but this should be whoever is logged into the application.

This is what I currently have.

Select * from dbo.CustomerList where usercode = 'BobS';

My guess is to use claims but I'm not sure why my code isn't working.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
carltonstith
  • 154
  • 3
  • 9
  • [This](https://stackoverflow.com/questions/30701006/how-to-get-the-current-logged-in-user-id-in-asp-net-core) should help. I also have to bring to your attention that next time do your research before rushing into questioning here. Effort is needed from both parties. – Ergis Dec 29 '20 at 14:56

1 Answers1

1

I'm assuming that at your entry point you already have the logged in User, most likely from the HttpContext. You could inject the UserManager into your current class and load the user via something like this.

var user = await _userManager.GetUserAsync(HttpContext.User);

This user object then should contain all the fields including custom fields of the efcore entity that you created.

You can then extend your efcore dbcontext to map results of raw sql queries and run something like this.

var customers = context.CustomerList
    .FromSqlInterpolated($"Select * from dbo.CustomerList where usercode = {user.Code}")
    .ToList();

For further reference you might consult the following links:

https://learn.microsoft.com/en-us/ef/core/querying/raw-sql

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1?view=aspnetcore-5.0

In general using ORM frameworks like the entity framework while coding most of the application logic inside of the database via stored procedures might not be the best approach. Usually I create most of the business logic in .NET querying necessary data via the ORM framework and only using store procedures / functions via the raw query option for performance critical scenarios or when the mapping of the ORM framework fails.

Frank
  • 21
  • 2