【问题标题】:Why is the data not stored when using SubmitChanges?为什么使用 SubmitChanges 时没有存储数据?
【发布时间】:2011-12-01 15:43:09
【问题描述】:

使用 MVC 创建 Player 类型的数据库条目:

[HttpPost]
public ActionResult Create(FormCollection fc, Player player)
{
    players.Players.InsertOnSubmit(player);
    players.SubmitChanges();

    Errors errors;
    if (!IsValid(player, out errors))
    {
        ViewBag.Errors = errors;
        return RedirectToAction("Edit", player);
    }

    return Redirect("/Home/Players");
}

[HttpPost]
public ActionResult Edit(FormCollection fc, Player player)
{
    players.SubmitChanges();

    return Redirect("/Home/Players");
}

我的问题是 Edit 方法中的 players.SubmitChanges() 不会更改数据库中的任何内容。在创建作品中使用InsertObSubmit。我要不要换一种方式?

【问题讨论】:

  • player 未附加到数据库。此外,这与 MVC 无关,而是与 Linq-to-SQL 或实体框架相关。 :)
  • 我应该如何以及在哪里将播放器附加到数据库?我假设它会知道它属于哪里,因为 Player 具有 global::System.Data.Linq.Mapping.TableAttribute(Name) 属性集。

标签: .net entity-framework linq-to-sql


【解决方案1】:
[HttpPost]
public ActionResult Edit(FormCollection fc, Player player)
{
    // I guess you are forgetting this
    players.Players.AttachAsModified(player)

    players.SubmitChanges();

    return Redirect("/Home/Players");
}

【讨论】:

  • 播放器中没有这种方法。只有 Attach() 和 AttachAll()。如果我在 asModified 设置为 true 的情况下使用 Attach(),则会收到异常“System.InvalidOperationException:如果实体声明版本成员或没有更新检查策略,则只能以修改后的状态附加没有原始状态。”
【解决方案2】:

当您将 Player 值作为 Edit 操作的输入参数时,您应该首先相应地修改您的 players 集合 - 这不会自动发生 - 然后才执行 players.SubmitChanges();

【讨论】:

  • “相应地修改玩家收藏”是什么意思?我该如何在代码中做到这一点?
猜你喜欢
  • 1970-01-01
  • 2017-10-17
  • 2020-09-10
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 2012-09-01
  • 2017-01-12
  • 1970-01-01
相关资源
最近更新 更多