MVC – Dealing with the Identity Column
February 2, 2010 4 Comments
I am following a MVC introduction tutorial found here. I have gone though it a couple of times and I am coming up to speed with the basics of MVC. I found an interesting error though. I created a controller called movie and then coded up the functions for the insertion of a movie record like this:
public ActionResult Create()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Movie movieToCreate)
{
if (ModelState.IsValid)
{
context.AddToMovieSet(movieToCreate);
context.SaveChanges();
return View(movieToCreate);
}
else
{
return View();
}
}
I then created a Unit Test to check my work like this (note the exclusion of the primary key):
public void CreateTest()
{
MovieController target = new MovieController();
Movie movieToCreate = new Movie();
movieToCreate.Title = "AAA";
movieToCreate.Director = "BBB";
movieToCreate.DateReleased = DateTime.Now;
ActionResult actual = target.Create(movieToCreate);
Assert.IsNotNull(actual);
}
Things worked great so I then created a View using the code generator (Right Click -> AddView) to create a data entry page. I then deleted the ID field because it is an identity key in the database:
Unfortunately, when I ran it, I got a validation error:
So I added back the ID Field and placed in a dummy value:
And the data took! Note the new ID number:
This illustrates my biggest problem with MVC so far – you need to rely almost exclusively on the Code Gen (and know the conventions) to get anything done and when things don’t work as expected, it is really hard to pinpoint the problem.
In this case, I found the error was that I didn’t tell the controller that the ID should not be bound. I changed the signature of the Create Function to this
public ActionResult Create([Bind(Exclude="Id")]Movie movie)
and it worked like a charm



