Note that there are some explanatory texts on larger screens.

plurals
  1. PORepository Methods vs. Extending IQueryable
    text
    copied!<p>I have repositories (e.g. ContactRepository, UserRepository and so forth) which encapsulate data access to the domain model. </p> <p>When I was looking at <em>searching for data</em>, e.g. </p> <ul> <li>finding a contact whose first name starts with XYZ</li> <li><p>a contact whose birthday is after 1960</p> <p>(etc),</p></li> </ul> <p>I started implementing repository methods such as <strong>FirstNameStartsWith(string prefix)</strong> and <strong>YoungerThanBirthYear(int year)</strong>, basically following the many examples out there.</p> <p>Then I hit a problem - what if I have to combine multiple searches? Each of my repository search methods, such as above, only return a finite set of actual domain objects. In search for a better way, I started writing <strong>extension methods</strong> on IQueryable&lt;T>, e.g. this:</p> <pre><code>public static IQueryable&lt;Contact&gt; FirstNameStartsWith( this IQueryable&lt;Contact&gt; contacts, String prefix) { return contacts.Where( contact =&gt; contact.FirstName.StartsWith(prefix)); } </code></pre> <p>Now I can do things such as</p> <pre><code>ContactRepository.GetAll().FirstNameStartsWith("tex").YoungerThanBirthYear(1960); </code></pre> <p>However, I found myself writing extension methods (and inventing crazy classes such as <strong>ContactsQueryableExtensions</strong> all over, and I lose the "nice grouping" by having everything in the appropriate repository.</p> <p>Is this really the way to do it, or is there a better way to achieve the same goal? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload