【问题标题】:I'm trying to Preserve/Protect certain fields in a View Model我正在尝试保留/保护视图模型中的某些字段
【发布时间】:2012-09-29 22:23:00
【问题描述】:

我正在尝试实现解决方案found here,但是一旦我将“用户”类替换为“EditUserViewModel”类(字段比用户类少的类)并且一旦我到达这一行

db.Entry(users).State = EntityState.Modified;

在这段代码中

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

我得到了错误

The entity type EditUserViewModel is not part of the model for the current context.

现在我猜这个错误是因为我的 DBContext 使用了 Users 类而不是 EditUserViewModel 类。我错过了一个步骤还是有什么办法可以解决这个问题?

【问题讨论】:

  • 你能发布EditUserViewModelUser的课程吗?
  • @Omar 发布课程
  • 如果我没看错,那么您就错过了新视图模型和相应域模型之间的映射。您的业​​务层可能无法(通常也不应该)知道如何直接持久化您的视图模型。
  • 已删除课程 b/c 我有答案,但认为课程不相关

标签: c# asp.net-mvc


【解决方案1】:

您需要将 MV 中的数据合并到 Model 类中。

if (ModelState.IsValid)
{
    var existingUser = db.Users.Single(p => /* query to find your user */);

    existingUser.From = user.From;
    existingUser.CC = user.CC;
    // etc.

    db.SaveChanges();

    return RedirectToAction("Index");
}

【讨论】:

  • 谢谢!这是我一直在寻找的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2016-06-16
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多