Right now, I have an enum like this:
public enum ReferenceType
{
Language = 1,
Period = 2,
Genre = 3
}
Language, Period, and Genre are all entity classes that map back to tables in my database. I also have model classes that map almost 1 to 1 with the entity classes, which I then display in a view.
I also have a service method like this:
List<Model> Get<Model, Entity>()
where Model : BaseModel
where Entity : BaseEntity;
I can call it like Service.Get<LanguageModel, Language>() and it will return every row from table Language from my database and automatically convert them into LanguageModels, which I’ll then display in my view.
I want to create a wrapper method around the Get() method where you simply need to pass in an integer and it will call my Get() method filling in the entity and model class types automatically. The only problem is I’m having a hard time wrapping my head around the actual implementation behind this.
The pseudo-code would be along the lines of:
- Call
WrapperGet((int)ReferenceType.Genre) - Wrapper method resolves the entity type (
Genre) and model type (GenreModel) - Call the
Get()method with the resolved entity and model types, so it’d beGet<GenreModel, Genre>() - Return the results
How would I actually go implementing this in C#?
If you want strongly-typed results, you’ll have to forgo the idea of passing an
intor enum in, and switch to callingGetdirectly or making methods like this:If weakly typed works for you, then I’d go with Saeed’s solution, but the types need a little changing to work.
Modelwas a generic type in your example, so presumably he meantList<BaseModel>as the return type. But aList<LanguageModel>isn’t aList<BaseModel>! You can resolve this by either making it returnIEnumerable<BaseModel>or changingGetto return aList<BaseModel>, or change it afterwards withreturn new List<BaseModel>(Get<...