MVC3使用用户名编辑客户

时间:2012-04-11 14:13:11

标签: asp.net-mvc-3 where

我正在尝试使用User.Identity.Name编辑客户。

我不知道如何在控制器中写出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);
    }

2 个答案:

答案 0 :(得分:4)

您需要了解lambda expressions的工作原理:

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

c是隐式类型参数。

此外,如果您想要一个结果,则应该拨打FirstOrDefault(); Where()返回一个序列。

答案 1 :(得分:0)

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

如果返回一个匹配元素

,则抛出异常

Customer customer = db.Customer.SingleOrDefault(c=>c.UserName == username);
如果返回多个匹配元素,

返回null

相关问题