Asp.net mvc 4 基于用户ID的MVC4查找用户名
我在VS2012中使用MVC4模板。我启用了一个comments部分,它将登录用户的UserId存储到一个表中。当我显示评论时,我想显示UserProfiles表中用户的用户名和电子邮件 我尝试了以下代码:Asp.net mvc 4 基于用户ID的MVC4查找用户名,asp.net-mvc-4,entity-framework-5,Asp.net Mvc 4,Entity Framework 5,我在VS2012中使用MVC4模板。我启用了一个comments部分,它将登录用户的UserId存储到一个表中。当我显示评论时,我想显示UserProfiles表中用户的用户名和电子邮件 我尝试了以下代码: public static string GetUserName(int userId) { using (var db = new UsersContext()) { return db.UserProfiles.Single(x => x.UserI
public static string GetUserName(int userId)
{
using (var db = new UsersContext())
{
return db.UserProfiles.Single(x => x.UserId == userId).UserName;
}
}
但我有一个例外:
The model backing the 'UsersContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
有什么建议吗?例外情况非常具有描述性。您的模型不能反映数据库的外观。我建议您阅读这篇文章,迁移的基本含义是更新数据库以匹配您的模型,在VS中只需一行命令即可完成 希望这有帮助
另外,我建议您使用
.Find()
或.First()
而不是。Single()
我通过删除表并重新添加来修复它。谢谢你的帮助。