Hello Imar,
in chapter 15 you create a hand-coded version of AddEditReview page - based on the Entity Framework and not on a SqlDataSourceControl.
However there is no handling of errors that may occur in the DB access.
For instance, if I try to update a review which, in the meantime, was deleted by another user of the applicaton I get a System.InvalidOperationException.
I've chosen to manage the exception in a try/catch and Response.Redirect the user to an error page, but I would like to know if there is a more elegant way to manage the DB exception within Entity Framework
like you did on page 562 where you caught a SqlException 547 from a SqlDataSource control.
Below my code.
Thanks
Antonius
Code:
protected void SaveButton_Click(object sender, EventArgs e)
{
try
{
using (PlanetWroxEntities istanzaDb = new PlanetWroxEntities())
{
Review myReview = null;
if (_id == -1) // Insert new item
{
myReview = new Review();
myReview.CreateDateTime = DateTime.Now;
myReview.UpdateDateTime = myReview.CreateDateTime;
istanzaDb.Reviews.Add(myReview);
}
else // update existing item
{
var counter = (from record in istanzaDb.Reviews
where record.Id == _id
select record).Count();
if (counter != 1)
{
ErrorMessage.Text = "The review was not found in the DB any more";
return;
}
else
{
myReview = (from record in istanzaDb.Reviews
where record.Id == _id
select record).Single();
myReview.UpdateDateTime = DateTime.Now;
} // end else
} // end else
myReview.Title = TitleText.Text;
myReview.Summary = SummaryText.Text;
myReview.Body = BodyText.Text;
myReview.GenreId = Convert.ToInt32(GenreList.SelectedValue);
myReview.Authorized = Authorized.Checked;
istanzaDb.SaveChanges();
Response.Redirect("Reviews.aspx");
} // end using
} // end try
catch (System.InvalidOperationException)
{
Response.Redirect("~/Errors/ErrorDbGeneric.aspx");
}
}