2012-04-11 58 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返回多个匹配的元素