Update database using restful ASP.NET MVC 1.0
We are building an MVC 1.0 application right now and using Linq -> SQL for our DAL. Following the restful approach we have multiple action events depending on if you are updating or loading or what not.
The two that I'm concerned with at this point are the edit and update action methods. Here is the signatures.
public ActionResult Update(int customerId, int Id, AggregateModel viewModel)
public ActionResult Edit(int customerId, int Id,开发者_运维百科 AggregateModel viewModel)
So the idea is that in the Edit method we load up our viewModel and pass it to the view. The user makes changes to the model and then posts back to the Update method.
The first thing I could think of to do would be to get the viewModel from the database again, copy the changes in one by one from the posted back model and then submit it back. This would work but does seem clunky to me.
What is the best way to insert those changes into the database at this point?
Do it the simple way, retrieving your model from the DB again, and updating the properties using either UpdateModel or manually. If you find that you are suffering performance problems and need to avoid the second query, then investigate detaching/reattaching the model from/to the DB and caching during the request cycle. Unless you actually have performance issues, I wouldn't invest effort in retaining the model over the request cycle.
You don't need to copy in the changes one by one. Use UpdateModel and the framework will copy in the changes for you.
If you use the repository pattern that should also take care of the loading of the data again. I don't think you can get around that unless you cache it which may be viable if you have a small dataset.
I use a dbml file as well as a datarepository class to get and set changes as well as insert and delete.
Article article = ar.FindAll(a => a.id == id).Single();
if (TryUpdateModel<Article>(article))
{
Where ar, above, is my repository.
If, however, you are transposing from one model to another google AutoMapper. That will map from one model to another though it doesn't sound like that's what your doing.
And looking at your actionresult I think it's a little overly complex. Mostly you'd have;
public ActionResult ArticleEdit(int id, FormCollection collection)
or
public ActionResult ArticleEdit(Article article)
The second is my flavour of choice.
精彩评论