I am trying to set up a generic interface to retrieve entities from a repository. The problem is that I need to request data from a WCF service and Generics don't work with operation contracts, from what I can see.
So I have this which works in a console application, not using a service call:
public virtual List<T> GetAll<T>() where T : MyBaseType
{
return this.datacontext.Set<T>().Include(l => l.RelationshipEntity).ToList();
}
The only way I could see dong this would be something like:
public virtual List<MyBaseType> GetAll(Type entityType)
{
return this.datacontext.Set(entityType).Include(l => l.RelationshipEntity).ToList();
}
Set<T>()
and Set(Type type)
both return a DbSet
but, Set(Type type)
doesn't have the extension to use ToList()
, nor do I get all my results back.
The Local
property is only showing the context in scope of the current execution, not what is contained in the repository.
So I want to have a WCF Contract like this:
[ServiceContract]
public interface IRulesService
{
[OperationContract]
MyBaseType Add(MyBaseType entity);
[OperationContract]
List<MyBaseType> GetAll(Type type);
}
Then the implementation:
public virtual List<MyBaseType> GetAll(Type entityType)
{
var dbset = this.datacontext.Set(entityType);
string sql = String.Format("select * from {0}s", type.Name);
Type listType = typeof(List<>).MakeGenericType(entityType);
List<MyBaseType> list = new List<MyBaseType>();
IEnumerator result = dbset.SqlQuery(sql).GetEnumerator();
while (result.MoveNext()){
list.Add(result.Current as MyBaseType);
}
return list;
}
//public virtual List<T> GetAll<T>() where T : MyBaseType
//{
// return this.datacontext.Set<T>().Include(l => l.RelationshipEntity).ToList();
//}
public virtual MyBaseType Add(MyBaseType entity)
{
DbSet set = this.datacontext.Set(typeof(entity));
set.Add(entity);
this.datacontext.SaveChanges();
return entity;
}
//public virtual T Add<T>(T t) where T : MyBaseType
//{
// this.datacontext.Set<T>().Add(t);
// this.datacontext.SaveChanges();
// return t;
//}
public virtual List<MyBaseType> UpdateAll(List<MyBaseType> entities)
{
}
Any ideas the best approach?