使用服务层进行验证,如何更新实体
我在我的应用程序中实现了一个服务层,例如: http://www.asp.net/learn/mvc/tutorial- 38-cs.aspx
(我使用Linq2SQL)。现在我在实现编辑 ActionResult 时遇到了麻烦。在创建(发布)ActionResult 中,我采用服务方法:
if (_service.CreateMovie(movie))
{
return RedirectToAction("Details", new { id = movie.ID });
}
else
{
return View(movie);
}
没关系。现在我在编辑ActionResult中的问题是:如何实现实体的更新?
在存储库中,我有以下更新方法:
public bool UpdateMovie(Film movieToUpdate)
{
try
{
_db.SubmitChanges();
return true;
}
catch
{
return false;
}
}
然后服务调用存储库。但是在表单中所做的更改不会“发送”到模型,因此实体不会被新值更新。
我可以在控制器中调用“UpdateModel”,但随后我还必须在服务中调用验证。但随后验证逻辑不再位于服务中,而是位于控制器中。
我希望你能理解我的问题。
I've implemented a service layer in my application like:
http://www.asp.net/learn/mvc/tutorial-38-cs.aspx
(I use Linq2SQL). Now I've trouble in implementing the Edit ActionResult. In the Create (Post) ActionResult I take the service method:
if (_service.CreateMovie(movie))
{
return RedirectToAction("Details", new { id = movie.ID });
}
else
{
return View(movie);
}
Thats okay. Now my problem in the Edit ActionResult is: how do I implement the update of an entity?
In the Repository I have following Update method:
public bool UpdateMovie(Film movieToUpdate)
{
try
{
_db.SubmitChanges();
return true;
}
catch
{
return false;
}
}
The Service then calls the Repository. But the changes made in the Form, are not "sended" to the model, so the entity was not updated by the new values.
I could call "UpdateModel" in the Controller, but then I must call also the Validate in the Service. But then the validation logic are no longer in the service than in the Controller.
I hope you understand my question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要首先检索新插入的电影,以便 L2S 知道它。然后将 movieToUpdate 发生的任何更改应用到这个新检索的电影对象,这将保留更改。请记住,您要将 SaveChanges 应用到与获取电影相同的上下文,否则 L2S 将不知道如何处理它。
You will need to first retrieve the newly inserted movie so that L2S knows about it. Then apply whatever changes happened from movieToUpdate to this newly retreived movie object and that will persist the changes. Remember that you want to apply SaveChanges to the same context as you did to get the movie, otherwise L2S won't know what to do with it.
如果没有基本类型验证,我没有找到任何更新模型的方法。所以我实现了 UpdateModel 和自定义 DefaultBinderMessage。目前这足以满足我的要求。
在其他地方,我可以实现错误接口来对服务层进行所有验证。
I don't found any method to update the model, without basic-type validation. So I've implemented UpdateModel and a custom DefaultBinderMessage. At the moment this is adequate for my claim.
Elsewhere I could implement the Error-Interface to do all validations with the service layer.