Asp.net mvc 如何将UserProfile模型传递给视图?

Asp.net mvc 如何将UserProfile模型传递给视图?,asp.net-mvc,simplemembership,Asp.net Mvc,Simplemembership,我试图在我的应用程序中实现简单的成员身份。我的问题是,我希望能够在userprofile表中为当前用户显示数据,但我不知道如何从DB中选择它 我已尝试过此操作,但出现了一个错误: UserProfile UserP = new UserProfile(); ViewBag.Message = User.Identity.Name; return View(); UserP = (from r in up.UserName

我试图在我的应用程序中实现简单的成员身份。我的问题是,我希望能够在userprofile表中为当前用户显示数据,但我不知道如何从DB中选择它

我已尝试过此操作,但出现了一个错误:

    UserProfile UserP = new UserProfile();

        ViewBag.Message = User.Identity.Name;
        return View();

        UserP = (from r in up.UserName
                  where up.UserName == User.Identity.Name.ToString()
                  select r).ToList().FirstOrDefault();


        return View(UserP);
以下是错误:

            Error   1   Cannot implicitly convert type 'char' to 'MvcApplication5.Models.UserProfile'   C:\Users\user\Desktop\MvcApplication5\MvcApplication5\Controllers\HomeController.cs 31  32  MvcApplication5
如果我理解正确(您的代码有点不完整,它有两个返回,因此我假设只有两段代码),请尝试以下操作:

UserP = (from r in up
                  where up.UserName == User.Identity.Name.ToString()
                  select r).FirstOrDefault();
只需在查询中去掉up.UserName即可。也不需要ToList()

关于未来,请注意:

我还建议您添加另一个名为LoweredUserName的列,并按以下方式执行检查:

where up.LoweredUserName == User.Identity.Name.ToString().ToLower()

下面是访问用户配置文件的方法

var context = new UsersContext();
var username = User.Identity.Name;
var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
return View(user);

了解更多信息。

你好,罗曼,非常感谢您的回复,但在这种情况下,“向上”是什么?通常它会引用DBContext,对吗?但当我试图运行ADO.Entity模型时,由于类重复,它产生了错误,所以我不知道“up”应该是什么???对不起,我没有说得很清楚。你能提供更多的应用程序代码吗?谢谢对不起,我还没有任何代码给你。我真正需要知道的是,我使用什么DBContext来访问UserProfile表数据???事实上,是的。您必须使用DbContext。它应该是这样的:var userProfile=context.UserProfiles.Where(up=>up.UserName==User.Identity.Name.ToString()).FirstOrDefault();上面的“上下文”和“向上”是什么?再次声明,我知道如何使用ADO.NET模型创建者正常访问表数据。但这些简单的成员资格表并不适用。。对不起,如果这是个愚蠢的问题嗨,凯文。谢谢你的回复,我在那里尝试了你的代码,但是我收到了一个错误。Visual studio给了我以下错误:初始化数据库时发生异常。有关详细信息,请参见InnerException。无法将文件“C:\Users\user\Desktop\mvcapapplication5\mvcapapplication5\App_Data\aspnet-mvcapapplication5-20131208163103.mdf”附加为数据库“aspnet-mvcapapplication5-20131208163103”。此错误与代码无关。EF在连接到为SimpleMembership配置的数据库时遇到问题。试试这个QA。[