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:
WrapperGet((int)ReferenceType.Genre)Genre) and model type (GenreModel)Get() method with the resolved entity and model types, so it'd be Get<GenreModel, Genre>()How would I actually go implementing this in C#?
I can't think for a full generic way, I think simplest way is as below:
List<Model> WrapperGet(int type)
{
switch (type)
{
case 1: return Get<LanguageModel, Language>();
....
}
return null;
}
If you want strongly-typed results, you'll have to forgo the idea of passing an int or enum in, and switch to calling Get directly or making methods like this:
List<LanguageModel> GetLanguages() { return Get<LanguageModel, Language>(); }
If weakly typed works for you, then I'd go with Saeed's solution, but the types need a little changing to work. Model was a generic type in your example, so presumably he meant List<BaseModel> as the return type. But a List<LanguageModel> isn't a List<BaseModel>! You can resolve this by either making it return IEnumerable<BaseModel> or changing Get to return a List<BaseModel>, or change it afterwards with return new List<BaseModel>(Get<...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With