LinqToSql MVC3 更新
我使用 ASP.NET MVC3 并作为数据层 LinqToSql。 我有点困惑如何编辑实体。
public ActionResult Edit(int id)
{
var product = _repository.GetById(id);
return View(product);
}
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
_repository.EditProduct(product);
return RedirectToAction("Index");
}
return View();
}
Edit() 中的变量product 是可以的,但是编辑后查看在 [HttpPost] Edit 中传递的变量 链接属性为 null,并且似乎与我的 DataContext 分离。 我还应该在 EditProduct 方法中执行什么代码来更新实体?
谢谢。
I use ASP.NET MVC3 and as Data layer LinqToSql.
I`m a little bit confuse how can i edit an entity.
public ActionResult Edit(int id)
{
var product = _repository.GetById(id);
return View(product);
}
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
_repository.EditProduct(product);
return RedirectToAction("Index");
}
return View();
}
Variable product in Edit() is ok, but after editing view the variable passed in [HttpPost] Edit
has null in link properties and seems to be detached from my DataContext.
And also what code should i execute in EditProduct method to update entity?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设在您的存储库中您有一个用于数据上下文的对象。在您的 EditProduct 调用中,您应该有类似的内容:
您还可以附加传入的产品并保存(如果您有时间戳列):
如果您没有时间戳列,则 L2S 将抛出有关无法检查的错误这是状态。
如果实体声明版本成员或没有更新检查策略,则只能以修改后的状态(没有原始状态)进行附加。
如果您向数据库添加时间戳列,则 L2S 可以执行上述操作。
这是一个更深入的解释。
I am assuming in your repository you have an object for your data context. In your EditProduct call you should have something like:
You can also attach the product coming in and save (if you have a timestamp column):
If you don't have a timestamp column then L2S will throw an error about not being able to check it's state.
An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
If you add a timestamp column to your DB then L2S can do the above.
Here's a deeper explanation.
(留给读者作为练习,让上面的代码处理异常、验证等)
(it's left as an exercise for the reader to make the code above handle exceptions, validation, etc.)
我找到了最适合我需求的方法
I have found method that best fits my needs