I am struggling on refactoring this (working) code:
MyDbContext db = new MyDbContext();
List<SelectListItem> selectedItems = new List<SelectListItem>();
if (type == null) return selectedItems;
if (type == typeof(class1))
selectedItems = db.class1.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).OrderBy(si => si.Text).ToList();
if (type == typeof(class2))
selectedItems = db.class2.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).ToList();
if (type == typeof(class3))
selectedItems = db.class3.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).ToList();
if (type == typeof(class4))
selectedItems = db.class4.ToList().Select(ii => new SelectListItem { Text = ii.Name, Value = ii.Id.ToString() }).ToList();
This code is inside an ASP.NET MVC controller. Class1 to Class 4 are Model classes.
SelectListItem is just a ModelView class I use to grab an Id and a Name from a Class1, 2, 3 or 4 object. I don't think it s worth posting its code. So below code just extracts all occurrences of Class1 or2 or 3 or 4 and converts them into options that will be passed to a View (for a DropDownBox). I only know the exact Model type at runtime of course (Class1...or 4).
I use Entity Framework with such a DbContext:
public partial class MyDbContext: DbContext
{
...
public virtual DbSet<Class1> Class1{ get; set; }
public virtual DbSet<Class2> Class2{ get; set; }
public virtual DbSet<Class3> Class3{ get; set; }
public virtual DbSet<Class4> Class4{ get; set; }
...
}
I am pretty sure I can end up with a clean code with reflection instead of this horrible thing I wrote. But I did not manage to get anything clean that compiles.
Thx for your help.
Aucun commentaire:
Enregistrer un commentaire