Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is an issue as old as the Repository pattern itself. The recent introduction of LINQ's <code>IQueryable</code>, a uniform representation of a query, has caused a lot of discussion about this very topic.</p> <p>I prefer specific repositories myself, after having worked very hard to build a generic repository framework. No matter what clever mechanism I tried, I always ended up at the same problem: a repository is a part of the domain being modeled, and that domain is not generic. Not every entity can be deleted, not every entity can be added, not every entity has a repository. Queries vary wildly; the repository API becomes as unique as the entity itself.</p> <p>A pattern I often use is to have specific repository interfaces, but a base class for the implementations. For example, using LINQ to SQL, you could do:</p> <pre><code>public abstract class Repository&lt;TEntity&gt; { private DataContext _dataContext; protected Repository(DataContext dataContext) { _dataContext = dataContext; } protected IQueryable&lt;TEntity&gt; Query { get { return _dataContext.GetTable&lt;TEntity&gt;(); } } protected void InsertOnCommit(TEntity entity) { _dataContext.GetTable&lt;TEntity&gt;().InsertOnCommit(entity); } protected void DeleteOnCommit(TEntity entity) { _dataContext.GetTable&lt;TEntity&gt;().DeleteOnCommit(entity); } } </code></pre> <p>Replace <code>DataContext</code> with your unit-of-work of choice. An example implementation might be:</p> <pre><code>public interface IUserRepository { User GetById(int id); IQueryable&lt;User&gt; GetLockedOutUsers(); void Insert(User user); } public class UserRepository : Repository&lt;User&gt;, IUserRepository { public UserRepository(DataContext dataContext) : base(dataContext) {} public User GetById(int id) { return Query.Where(user =&gt; user.Id == id).SingleOrDefault(); } public IQueryable&lt;User&gt; GetLockedOutUsers() { return Query.Where(user =&gt; user.IsLockedOut); } public void Insert(User user) { InsertOnCommit(user); } } </code></pre> <p>Notice the public API of the repository does not allow users to be deleted. Also, exposing <code>IQueryable</code> is a whole other can of worms - there are as many opinions as belly buttons on that topic. </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