When you have a number of items to insert into DB from a ASP.NET MVC app (like a collection of posted files) do you perform most of the exception handling logic in the controller or inisde the repository?
Do you do this
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Import(HttpPostedFileBase fileToUpload)
{
string path = Server.MapPath("~/App_Data/Upload/") + Path.GetFileName(fileToUpload.FileName);
fileToUpload.SaveAs(path);
string selectCmd = "SELECT * FROM [Pricelist$]";
try {
foreach (DataRow dr in ExcelUtility.ReadFile(path, selectCmd).Tables[0].Rows) {
Product p = new Product
{
Title = dr["product_name1"].ToString().Trim(),
Measure = dr["product_measure"].ToString().Trim(),
};
if (dr["product_price"] != DBNull.Value)
p.Price = (double)dr["product_price"];
if (dr["product_taxrate"] != DBNull.Value)
p.TaxRate = (double)dr["product_taxrate"];
_repository.Add(p);
}
}
catch (Exception e) {
// handle exception or run the action in transaction??
}
return RedirectToAction("ImportSuccessful");
}
or something else (maybe handle the exception in the repository and have repository action return true/false based on whether the method was successfully executed or not)?
Since my question wasn’t formulated to the best of my abilities because I didn’t actually know what exactly I would like for the answer, I’m going to post the solution that I’ve came up with in this last day.
First, my repository handles all of the data functions. Second, my repository method return true/false whether the data insertions were successful (there may be problems with inserting into database that are not exceptions, just some business rules failing).
Third, my repository method builds a report that is returned via output params.
This is the controller action code now:
And this is the repository interface:
I think this is as optimal as it gets..but if someone has a comment on it, be my guest.