A generic linq-to-sql class for easy, strongly-typed data access
Repository interface:
public interface IRepository<T>
{
IEnumerable<T> GetAll();
IEnumerable<T> Get(Func<T, bool> exp);
void Insert(T entity);
void CommitChanges();
}
Implementation:
public class LinqToSqlRepository<T> : IRepository<T> where T : class
{
private DataContext _db;
public LinqToSqlRepository(DataContext db)
{
_db = db;
}
protected Table<T> GetTable()
{
return _db.GetTable<T>();
}
public IEnumerable<T> GetAll()
{
return GetTable().AsQueryable();
}
public IEnumerable<T> Get(Func<T, bool> exp)
{
return GetTable().Where(exp);
}
public void Insert(T entity)
{
GetTable().InsertOnSubmit(entity);
}
public void CommitChanges()
{
_db.SubmitChanges();
}
}
A fake repository for used with tests:
public class InMemoryRepository<T> : IRepository<T> where T : class
{
private readonly IList<T> _storage;
public InMemoryRepository(IList<T> storage)
{
_storage = storage;
}
public IEnumerable<T> GetAll()
{
return _storage.AsEnumerable();
}
public IEnumerable<T> Get(Func<T, bool> exp)
{
return _storage.Where(exp);
}
public void Insert(T entity)
{
_storage.Add(entity);
}
public void CommitChanges()
{
}
}
The DataContext passed to LinqToSqlRepository should be a UoW implementation. The repository could handle all the disposal by itself but i found it more useful to do explicitly do that.
Fork
2 Feedback
What happens if you don't need Insert in some of your repositories? - @johannormen Thursday 30, 2010 1:35 PM
What about disposing the external resources as the db connection? - @lennybacon Thursday 21, 2010 11:39 AMYou must log in before you can give any feedback
0
@johannormen Well, in this case you must implement the Insert method signature, but you can skip implementing the method body.
0
public interface IRepository<T> : IDisposable
{
IEnumerable<T> GetAll();
IEnumerable<T> Get(Func<T, bool> exp);
void Insert(T entity);
void CommitChanges();
}
public class LinqToSqlRepository<T> : IRepository<T> where T : class
{
private DataContext _db;
public LinqToSqlRepository()
{
var connStr =
ConfigurationManager.
ConnectionStrings["RepositoryConnection"].
ConnectionString;
_db = new DataContext(connStr);
}
public LinqToSqlRepository(DataContext db)
{
_db = db;
}
protected Table<T> GetTable()
{
return _db.GetTable<T>();
}
public IEnumerable<T> GetAll()
{
return GetTable().AsQueryable();
}
public IEnumerable<T> Get(Func<T, bool> exp)
{
return GetTable().Where(exp);
}
public void Insert(T entity)
{
GetTable().InsertOnSubmit(entity);
}
public void CommitChanges()
{
_db.SubmitChanges();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
_db.Dispose();
}
}
0
You must log in before you can post a comment


1.04k
0

Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'