You could certainly encapsulate this into a method that returns dynamic
, although you lose your type safety and always with dynamic, a bit of performance.
public dynamic DynamicSelect(Expression<Func<Address, dynamic>> query)
{
return Addresses.Select(query).Take(1).ToList();
}
You can then call it and retrieve data from it like so:
var result = DynamicSelect(q => new {q.Id, q.AddressLine1});
Console.WriteLine(result[0].Id);
When using DbSets
, you can even take this a step further and genericize it:
public dynamic DynamicSelect<TEntity>(Expression<Func<TEntity, dynamic>> query)
{
return context.DbSet<TEntity>.Select(query).Take(1).ToList();
}
Personally I'd ask yourself if this type of flexibility is really necessary. You're killing your type safety for a marginal increase in "flexibility".