问题
I have an interface
public interface IFetchData<TEntity>
{
IEnumerable<TEntity> GetItems();
}
Two classes inherit from this interface FetchFromDatabase and FetchFromCollection. The purpose is to switch between classes injected to another class that let's say present them on screen etc. Depending on type used, I would like to fetch data from a particular collection depending on a type. It was not a problem to implement this functionality in FetchFromDatabase because DbContext has method DbContext.Set<>() which returns particular table.
I am looking for the way to do it using collections. In FetchFromCollection in line 23: return modules.Set();, compiler reports error:
Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<MainProgram.Models.Module>' to 'System.Collections.Generic.IEnumerable<TEntity>'. An explicit conversion exists (are you missing a cast?)
I don't know how to convert Module class to generic type TEntity. I tried to use intermediate class ModelBase and inherit to concrete definitions but then I would have to use another level of injection and decide by myself to which concrete class to use.
I found something here Pass An Instantiated System.Type as a Type Parameter for a Generic Class which is the way of using reflection. I am still confused how to achieve this. Any suggestions please?
FetchFromDatabase
public class FetchFromDatabase<TEntity> : IFetchData<TEntity>
where TEntity : class
{
private readonly MainDBContextBase context;
public FetchFromDatabase(MainDBContextBase context)
{
if (context == null)
throw new ArgumentNullException("DB context");
this.context = context;
}
public IEnumerable<TEntity> GetItems()
{
return context.Set<TEntity>();
}
}
FetchFromCollection
public class FetchFromCollection<TEntity> : IFetchData<TEntity>
where TEntity : class
{
private readonly InitializeComponents components;
private ModelModules modules;
private ModelSpecializations specializations;
private ModelTeachers techers;
private ModelStudents students;
public FetchFromCollection(InitializeComponents components)
{
if (components == null)
throw new ArgumentNullException("Context");
this.components = components;
}
public IEnumerable<TEntity> GetItems()
{
if (typeof(TEntity) == typeof(Module))
{
if (modules == null)
modules = new ModelModules(components);
return modules.Set();
}
return null;
}
}
回答1:
Did you try explicit cast?
return (IEnumerable<TEntity>)modules.Set();
来源:https://stackoverflow.com/questions/32922880/generic-class-to-return-particular-set-of-data-depending-on-type