Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric Repository Pattern with UnitOfWork Pattern
    text
    copied!<p>I am trying to implement a generic repository pattern. I found this site which I think its well explained. <a href="http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle">http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle</a></p> <p>My purpose is to save the developers some time and keystrokes and I know this will help me.</p> <p>So I have 2 questions:<br> 1. Is this a good approach or not, will I have some problems in the future?<br> 2. How can I combine it with Unitofwork pattern?, I cant create an instance of the abstract class of course, so the following code its invalid.</p> <pre><code>public class UnitOfWork : IDisposable { #region Private fields private readonly MyCompanyContext _context = new MyCompanyContext(); private GenericRepository&lt;MyCompanyContext, Task&gt; _taskRepository; public GenericRepository&lt;MyCompanyContext, Task&gt; TaskRepository { get { return _taskRepository ?? (_taskRepository = new GenericRepository&lt;MyCompanyContext, Task&gt;()); } } namespace MyCompany.DAL.Repository { public interface IGenericRepository&lt;T&gt; where T : class { IQueryable&lt;T&gt; GetAll(); IQueryable&lt;T&gt; FindBy(Expression&lt;Func&lt;T, bool&gt;&gt; predicate); void Add(T entity); void Delete(T entity); void Edit(T entity); void Save(); } public abstract class GenericRepository&lt;C, T&gt; : IGenericRepository&lt;T&gt; where T : class where C : DbContext, new() { private C _entities = new C(); public C Context { get { return _entities; } set { _entities = value; } } public virtual IQueryable&lt;T&gt; GetAll() { IQueryable&lt;T&gt; query = _entities.Set&lt;T&gt;(); return query; } public IQueryable&lt;T&gt; FindBy(System.Linq.Expressions.Expression&lt;Func&lt;T, bool&gt;&gt; predicate) { IQueryable&lt;T&gt; query = _entities.Set&lt;T&gt;().Where(predicate); return query; } public virtual void Add(T entity) { _entities.Set&lt;T&gt;().Add(entity); } public virtual void Delete(T entity) { _entities.Set&lt;T&gt;().Remove(entity); } public virtual void Edit(T entity) { _entities.Entry(entity).State = System.Data.EntityState.Modified; } public virtual void Save() { _entities.SaveChanges(); } } } </code></pre>
 

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