Last active
August 29, 2015 13:57
-
-
Save claudiosanchez/a663c5625d98df22d49c to your computer and use it in GitHub Desktop.
A Super Get Method in a Generic repository implementation, using Entity Framework. Source(s): http://blog.falafel.com/Blogs/AdamAnderson/adam-anderson/2014/02/28/the-four-deadly-sins-of-linq-data-access-part-2-too-many-columns http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patt…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
// _repository is a GenericRepository<Villa>. | |
var villas = _repository | |
.Get( | |
q => q.Select(s => new VillaDto { | |
Id = s.PodId, | |
Name = s.Name, | |
Price=s.Price, | |
Location = s.Location }), | |
f => f.Location == "Punta Cana", | |
o => o.OrderBy(i => i.Price) | |
); | |
... | |
public IEnumerable<TResult> SuperGet<TResult>( | |
Func<IQueryable<TEntity>, IQueryable<TResult>> transform, | |
Expression<Func<TEntity, bool>> filter = null, | |
Func<IQueryable<TResult>, IOrderedQueryable<TResult>> orderBy = null) | |
{ | |
// _dbSet is DbSet<TEntity> property of a DbContext | |
var query = (filter == null) ? _dbSet : _dbSet.Where(filter); | |
var notSortedResults = transform(query); | |
return orderBy == null ? (IEnumerable<TResult>) notSortedResults : orderBy(notSortedResults).ToList(); | |
} |
Javier, haz el pull request para aceptar tu aporte en el repo.
No he realizado el Pull Request con el cambio porque se me queda en el trabajo :P Manana lo hago.
Tengo varias preguntas para ustedes dos. Si yo tengo 5 condiciones en el filtro pero son opcionales, como le hago para que en el Query que se ejecuta en la base de datos, las que son opcionales ni siquiera aparezcan en el WHERE? Pienso que es lo que hace falta ahora mismo.
A que te refieres cuando dices que tus condiciones son opcionales?
Puedes proveer un ejemplo concreto?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh ok, ya entiendo.. el transform es el mapper.. como con el
ExecuteFunction
se mapean las propiedades automaticamente de acuerdo al nombre.. no pense era necesario el transform.. pero eso de objectParameters si es un lio..^_^Reflexion for the win! ^_^