I need help refactoring this code to dynamically generate a sort string that I can send to my data layer so that my database does the sorting instead of it happening in memory. I am using MVC4 with EF5 as my data layer.
public ActionResult InstanceSearch(int? page, string sortOrder, string computerName, string instanceName,
string productName, string version)
{
int pageSize = 10;
int pageNumber = (page ?? 1);
if (pageNumber < 1)
{
pageNumber = 1;
}
if (string.IsNullOrEmpty(sortOrder))
{
sortOrder = "Computer";
}
ViewBag.CurrentSort = sortOrder;
ViewBag.ComputerSort = sortOrder == "Computer" ? "ComputerDesc" : "Computer";
ViewBag.InstanceSort = sortOrder == "Instance" ? "InstanceDesc" : "Instance";
ViewBag.VersionSort = sortOrder == "Version" ? "VersionDesc" : "Version";
ViewBag.ProductSort = sortOrder == "Product" ? "ProductDesc" : "Product";
//IEnumerable<Instance> instances = ecuWebDataContext.Instances;
IQueryable<Instance> instances
= string.IsNullOrEmpty(computerName) == true ? ecuWebDataContext.Instances : ecuWebDataContext.Instances.Where(i => i.Computer.Name == computerName);
if (string.IsNullOrEmpty(instanceName) == false)
{
instances = instances.Where(i => i.Name == instanceName);
}
if (!string.IsNullOrEmpty(productName))
{
ProductName product = (ProductName)Enum.Parse(typeof(ProductName), productName);
instances = instances.Where(i => i.Product.Name == product);
}
if (!string.IsNullOrEmpty(version))
{
instances = instances.Where(i => i.Version == version);
}
switch (sortOrder)
{
case "Computer":
instances = instances.OrderBy(i => i.Computer.Name);
break;
case "ComputerDesc":
instances = instances.OrderByDescending(i => i.Computer.Name);
break;
case "Instance":
instances = instances.OrderBy(i => i.Name);
break;
case "InstanceDesc":
instances = instances.OrderByDescending(i => i.Name);
break;
case "Version":
instances = instances.OrderBy(i => i.Version);
break;
case "VersionDesc":
instances = instances.OrderByDescending(i => i.Version);
break;
case "Product":
instances = instances.OrderBy(i => i.Product.Name);
//instances = instances.OrderBy(i => Enum.Parse(typeof(ProductName), i.Product.Name));
break;
case "ProductDesc":
instances = instances.OrderByDescending(i => i.Product.Name);
//instances = instances.OrderByDescending(i => Enum.Parse(typeof(ProductName), i.Product.Name));
break;
}
ViewBag.SortOrder = sortOrder;
var instanceSearchModel = new InstanceSearchModel { ComputerName = computerName, InstanceName = instanceName };
ViewBag.ComputerName = computerName;
ViewBag.InstanceName = instanceName;
ViewBag.ProductName = productName;
ViewBag.InstanceCount = instances.Count();
ViewBag.Version = version;
return View(instances.ToPagedList(pageNumber, pageSize));
}
I tried returning an IQueryable from the data layer, but then I run into connection problems because I never close it.