CzarnePaski CzarnePaski - 22 days ago 6
C# Question

How to get more information than username about current user in Asp.Net MVC

I'm beginner in programming and I've got a problem with select data from database. I can get current user username (in my database it's unique for every user). I'd like to get from database more information about this user - Id, name, surname. I don't know how to do this.

I made DbContext:

namespace Aplikacja.DAL
{
public class AplikacjaContext : DbContext
{
public DbSet<Konto> MojeKonto { get; set; }
}
}


This is in my controller:

public ActionResult MojeKonto()
{
var konto = new Konto
{
pesel = User.Identity.Name,
};
return View(konto);
}


This is part of model:

public class Konto
{
public int idUzytkownik { get; set; }
public string imie { get; set; }
public string nazwisko { get; set; }
public string pesel { get; set; }
public string haslo { get; set; }
}


I use "pesel" as username.

I tried something like this in controller:

var user = from u in ***
where u = User.Identity.Name
select u


***- here I've got a problem, because intelisence doesn't see database. Should I change something in my program or try different way?

Answer

It is fine to load from the database using the username found in User.Identity.Name.

Code similar to the below will do what you need and get you the full user object from your database, you simply need to instantiate your DbContext before using it in your proposed LINQ query. That's why it didn't work. Also, using SingleOrDefault (as below) is also a better idea as it will pull out the only record (or none if it can't be found) since they're unique anyway.

public ActionResult MojeKonto()
{
    // Initialise a blank variable for if they're not logged in, or are an invalid user
    Konto konto = null;
    // Only try to load if they're logged in
    if (User.Identity.IsAuthenticated) {
        // Instantiate the DbContext to connect to database
        using(var db = new AplikacjaContext()) {
            // Attempt to load from database using Username, note that 'OrDefault' means if it doesn't exist, "konto" variable will stay null
            konto = db.MojeKonto.SingleOrDefault(m => m.pesel == User.Identity.Name);
        }
    }

    if (konto == null) {
        // You could do something here if you can't load more detail about the user if you wanted
    }

    return View(konto);
}