I’m building a simple MVC Movie Application, using a repository pattern and Class Library for my Linq to SQL Classes. I can’t seem to get my objects to UPDATE back to the database.. I’m missing something now sure what it is:
public class MovieRepository : BaseRepository, IMovieRepository
{
/// <summary>
/// Updates the specified movie.
/// </summary>
public void Update()
{
GetDataContext.SubmitChanges();
}
/// <summary>
/// Fetches the by id.
/// </summary>
/// <param name="id">The id.</param>
public Movie FetchById(int id)
{
Movie movie = (from n in GetDataContext.Movies
where n.ID == id
select n).First();
return movie;
}
}
BaseRepository.cs
public abstract class BaseRepository
{
private static VideoStoreDBDataContext _videoStoreDbDataContext;
protected static VideoStoreDBDataContext GetDataContext
{
get
{
if (_videoStoreDbDataContext == null)
{
_videoStoreDbDataContext = new VideoStoreDBDataContext();
}
return _videoStoreDbDataContext;
}
}
}
HomeController
public ActionResult EditMovie(int Id)
{
Movie movie = _movieRepository.FetchById(Id);
if (movie == null)
return RedirectToAction("Error", "Home");
return View(movie);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditMovie(Movie movie)
{
if (!ModelState.IsValid)
return View(movie);
// NOTE: movie object does infact contain changes made using the VIEW.
_movieRepository.Update();
return RedirectToAction("Index");
}
View
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Details</legend>
<p>
<label for="Title">Title:</label><br/>
<%= Html.TextBox("Title", Model.Title) %>
<%= Html.ValidationMessage("Title", "*") %>
</p>
<p>
<input type="submit" value="Update Movie" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
In your method
EditMovie, the objectmoviethat you receive as the argument, is not actually a database-bound object. It gets constructed for you by MVC runtime, and yourDataContexthas no knowledge of it. Therefore, when you callUpdate(), theDataContextdoesn’t see any changes to write to the database.What you should do instead is find this object in the database, then copy all fields from the method’s argument into it, and then call
Update(). Like so:For this to work, you also have to include your Movie’s ID in your form (as a hidden field), so that it may be posted back by the browser, and thus enable you to distinguish update to one movie from update to another. Like so:
EDIT: As Mystere Man pointed out, you do not need to add this hidden field if your URL contains the Id.