Unit of Work パターンに従ってインターフェイスを作成しています。私のインターフェースは次のようになります。
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 でそれらをチェーンすることはできますが、それでもかなりひどいように見えます。その他の問題は、追加される可能性のある新しいエンティティごとに 1 行を手動で追加する必要があることですが、それは私の主な関心事ではありません。
誰でもこれについて何か良いアドバイスはありますか? ありがとう。