Say I have 3 tables in my database: people, tasks and projects
Say I have 3 classes for repository’s: PeopleRepository, TaskRepository and ProjectRepository.
Now I want a single method, that will work with any of these classes.
Obviously I could just write out loads of code for each table, but I’d rather keep code down to a minimum. I already have reflection working fine for the different column names that might be passed to the method, but I can’t seem to get code like this to work.
switch (tableName)
{
case "people":
var repository = new PeopleRepository();
break;
case "tasks":
var repository = new TaskRepository();
break;
case "projects":
var repository = new ProjectRepository();
break;
}
//Modify respective database table
repository.getItem(id); //etc
repository.Save(); //etc
I’ve tried a few other things like this, but none of them seemed to work. Changing the scope of where the variable is defined etc.
I feel like c# should have something nice to deal with this, is this so? Or do I have to write the same code in each switch statement?
You could make an interface that those classes would implement. Then use
You can also make repository
dynamicAnd the type will be resolved in runtime.