2012-04-11 6 views
0

私はUser.Identity.Nameを使用しているユーザー名で顧客を編集しようとしています。MVC3ユーザー名を編集する(

コントローラのWhere条件を書き込む方法がわかりません。

これは簡単です。私たちを手伝ってくれますか?ありがとう。

ここに私のコーディングがあります。

[Authorize] 
    public ActionResult Edit() 
    { 
     //the username gets username through User.Identity.Name. 
     string username = User.Identity.Name; 

     //How can I write below coding? 
     //In DB, it has userName field. 

     Customer customer = db.Customer.Where(userName = username); 
     return View(customer); 
    } 

[HttpPost] 
    public ActionResult Edit(Customer customer) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Entry(customer).State = EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(customer); 
    } 

答えて

4

あなたはlambda expressions作業方法を学ぶ必要があります。

.Where(c => c.UserName == username) 

cが暗黙に型付けされたパラメータです。

また、1つの結果が必要な場合は、代わりにFirstOrDefault()を呼び出す必要があります。 Where()はシーケンスを返します。

+0

よりもリターンは多くの場合、それは「暗黙的にタイプを変換することができないと言う例外をスローSystem.Linqの.Iqueryable をModels.Customerに追加します。どういう意味ですか? – wholee1

+0

@ wholee1:エラーメッセージのどの部分を理解していませんか? – SLaks

+0

Oh .. FirstOrDefault()を置くと動作します。ありがとう! – wholee1

0
Customer customer = db.Customer.Single(c=>c.UserName == username) 

戻り以上のマッチング要素より1

または

Customer customer = db.Customer.SingleOrDefault(c=>c.UserName == username); 

戻っnullの場合は、1つのマッチング要素

関連する問題