2012-04-11 57 views
0

我正在嘗試使用User.Identity.Name用戶名編輯客戶。MVC3使用用戶名編輯客戶

我不知道如何寫在控制器的條件。

看起來很簡單。你可以幫幫我嗎?謝謝。

這是我的編碼。

[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是隱式類型的參數。

此外,如果您想獲得單個結果,則應該調用FirstOrDefault()代替; Where()返回一個序列。

+0

它說不能隱式轉換類型「System.Linq的。查詢到Models.Customer。這是什麼意思? – wholee1 2012-04-11 14:20:10

+0

@ wholee1:你不明白哪部分錯誤信息? – SLaks 2012-04-11 14:21:11

+0

Oh..when我把FirstOrDefault(),它的作品。謝謝! – wholee1 2012-04-11 14:23:33

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

拋出異常,如果回報率超過一人匹配的元素

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

,則返回null返回多個匹配的元素