2013-03-23 15 views
0

我在VS 2012中使用了MVC 4模板。我啓用了將註冊用戶的UserId存儲到表中的評論部分。當我顯示評論時,我想從UserProfiles表中顯示用戶的用戶名和電子郵件。MVC 4查找基於UserId的用戶名

我試過下面的代碼:

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

有什麼建議?

回答

0

這個例外很具描述性。您的模型不能反映您的數據庫的外觀。我建議你閱讀關於code first migrations的這個,基本上,遷移的意思是你更新你的數據庫來匹配你的模型,它在VS中用一行命令完成。

希望這有助於

此外,我建議你刪除表,並重新添加它使用的.Single().Find().First()代替

+0

我固定它。感謝您的幫助。 – kip 2013-03-23 21:04:38