基于UserId的MVC 4查找用户名

时间:2013-03-23 15:44:24

标签: asp.net-mvc-4 entity-framework-5

我在VS 2012中使用MVC 4模板。我启用了一个注释部分,用于将登录用户的UserId存储到表中。当我显示评论时,我想从UserProfiles表中显示用户的用户名和电子邮件。

我尝试过以下代码:

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).

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

该例外非常具有描述性。您的模型不反映数据库的外观。我建议您阅读有关code first migrations的内容,基本上,迁移的意思是您更新数据库以匹配模型,在VS中使用一行命令完成。

希望这有帮助

我还建议您使用.Find().First()代替.Single()

相关问题