I’m making an interface following the Unit of Work pattern. My interface looks like this:
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>();
}
So far so good. Now I implement it in my Data Layer, which uses EF4 as data provider. I came up with this code for the “Query” method, but I think it’s not very clean, I feel there’s a clever way to do it but I can’t really figure out.
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));
}
The problems I see here are all the IFs get tested every time, althought I could chain them in a cascading if-else but still looks pretty awful to me. The other problems is that I have to manually add one line for each new entity that might get added, but it’s not my main concern.
Anyone has any good advice on this? Thanks.
If you are using EF4 you can just call CreateObjectSet<>.
If you are using EF1 you can call CreateQuery<> but you will also need to find the Entity
Set Name.