如何获取有关Asp.Net MVC中当前用户的用户名的更多信息

时间:2016-11-15 19:34:28

标签: c# .net asp.net-mvc

我是编程初学者,我从数据库中选择数据时遇到了问题。我可以获得当前用户的用户名(在我的数据库中,它对每个用户都是唯一的)。我想从数据库获取有关此用户的更多信息 - Id,name,surname。我不知道该怎么做。

我制作了DbContext:

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

这是在我的控制器中:

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

这是模型的一部分:

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

我使用&#34; pesel&#34;作为用户名。

我在控制器中试过这样的事情:

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

*** - 我在这里遇到了问题,因为知识并没有看到数据库。我应该改变程序中的某些内容还是尝试不同的方式?

1 个答案:

答案 0 :(得分:0)

可以使用User.Identity.Name中的用户名从数据库加载。

类似于下面的代码将执行您所需的操作并从数据库中获取完整的用户对象,您只需在建议的LINQ查询中使用它之前实例化DbContext。这就是为什么它不起作用。也, 使用SingleOrDefault(如下所示)也是一个更好的主意,因为它会拉出唯一的记录(如果无法找到,则没有记录),因为它们无论如何都是唯一的。

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