根据类型返回特定数据集的泛型类
本文关键字:数据集 泛型类 类型 返回 | 更新日期: 2023-09-27 18:15:54
我有一个接口
public interface IFetchData<TEntity>
{
IEnumerable<TEntity> GetItems();
}
两个类从这个接口继承FetchFromDatabase
和FetchFromCollection
。目的是在注入到另一个类的类之间切换,比如在屏幕上显示它们等等。根据所使用的类型,我希望根据类型从特定集合中获取数据。在FetchFromDatabase
中实现此功能不是问题,因为DbContext
具有返回特定表的DbContext.Set<>()
方法。
我正在寻找使用集合的方法。在FetchFromCollection
的第23行:return modules.Set();
,编译器报告错误:
错误2无法隐式转换类型'System.Collections.Generic.IEnumerable
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; } }
你试过显式强制转换吗?
return (IEnumerable<TEntity>)modules.Set();