I'm using LINQ-to-Entities. Using the following query:
var x = from u in context.Users select new { u.Id, u.Name };
That only selects the Id
and Name
columns. Great.
I'm trying to make a repository that can be passed that new { u.Id, u.Name}
as a parameter to allow the client to pick which columns are used in the SELECT statement.
I'm trying to use the "fluent" interface with my repository instead of the query syntax. Basically the final call is to convert IQueryable to IList and actually execute the code. I've looked at the DynamicExpressions library but I'm not really sure this is the route I want to take for this. It's possible to do it with the query syntax, but not the fluent interface?
Edit: Sorry I should have mentioned that all queries are encapsulated inside the repository. So for example I want to be able to expose a method like the following:
public void Project(Expression<Func<TEntity, TEntity>> fields)
{
this.Projection = fields;
}
So calling this would be like:
using (DBContext context = new DBContext())
{
IUserRepository repo = new UserRepository(context);
repo.Project(u => new { u.Id, u.Name });
repo.GetById(100);
}
Inside of GetById
would be something like ctx.Users.Where(u => u.Id == id).Select(this.Projection)
.
This way, which columns are returned can be selected by the calling code. The reason for this is because maybe I want to return a User object but maybe I only need the Id and Name (and thus returning less data over the wire).
The problem is that I obviously can't convert the anonymous type to User. It would be cool if I could do something like:
repo.Project(u => new User() { Id = u.Id, Name = u.Name });
Which would mean I don't need to create an anonymous on type. EDIT: Ok this seems to work ONLY if the type that's returned is a POCO ... ugh.
EDIT2: I might have to go the DLINQ approach. What I'm thinking is having Expression<Func<TEntity, object>>
(to use the anonymous type) and then use reflection to get the list of properties. Then, using DLINQ build a string expression. The only downside is that I don't really want to use DLINQ as it adds a little overhead (Reflection.Emit etc..).