我正在按照工作单元模式制作一个界面。我的界面如下所示:
public interface IDataContext : IDisposable
{
void SaveChanges();
TSource Create<TSource>(TSource toCreate) where TSource : class;
TSource Update<TSource>(TSource toUpdate) where TSource : class;
bool Delete<TSource>(TSource toDelete) where TSource : class;
IQueryable<TSource> Query<TSource>();
}
到现在为止还挺好。现在我在我的数据层中实现它,它使用 EF4 作为数据提供者。我为“查询”方法想出了这段代码,但我认为它不是很干净,我觉得有一个聪明的方法可以做到,但我真的想不通。
public IQueryable<TSource> Query<TSource>()
{
var type = typeof(TSource);
IQueryable item = null;
if (type == typeof(Activity)) item = _entities.ActivitySet;
if (type == typeof(Company)) item = _entities.CompanySet;
if (type == typeof(Phase)) item = _entities.PhasesSet;
if (type == typeof(Project)) item = _entities.ProjectSet;
if (type == typeof(ProjectState)) item = _entities.ProjectStateSet;
if (type == typeof(ProjectType)) item = _entities.ProjectTypeSet;
if (type == typeof(User)) item = _entities.UserSet;
if (type == typeof(UserType)) item = _entities.UserTypeSet;
if (item != null) return item as IQueryable<TSource>;
throw new NotImplementedException(string.Format("Query not implemented for type {0}", type.FullName));
}
我在这里看到的问题是所有 IF 每次都经过测试,尽管我可以将它们链接在级联的 if-else 中,但对我来说仍然看起来很糟糕。另一个问题是我必须为每个可能添加的新实体手动添加一行,但这不是我主要关心的问题。
有人对此有什么好的建议吗?谢谢。