Skip to content

Instantly share code, notes, and snippets.

@derans
Last active October 2, 2015 00:08
Show Gist options
  • Save derans/2131508 to your computer and use it in GitHub Desktop.
Save derans/2131508 to your computer and use it in GitHub Desktop.
L2S Repository
public abstract class LinqToSqlRepository : IDisposable
{
private readonly DataContext _dc;
protected LinqToSqlRepository()
{
_dc = DataContext;
}
public T Load<T>(object id) where T : class
{
return _dc.GetTable<T>().SingleOrDefault(BuildWhereClause<T>(id));
}
public void Update<T>(T entity) where T : class
{
_dc.SubmitChanges();
}
public void Insert<T>(T entity) where T : class
{
_dc.GetTable<T>().InsertOnSubmit(entity);
_dc.SubmitChanges();
}
public void Insert<T>(IEnumerable<T> entities) where T : class
{
_dc.GetTable<T>().InsertAllOnSubmit(entities);
_dc.SubmitChanges();
}
public IQueryable<T> Query<T>() where T : class
{
return _dc.GetTable<T>();
}
public void Delete<T>(T entity) where T : class
{
_dc.GetTable<T>().DeleteOnSubmit(entity);
_dc.SubmitChanges();
}
public void DeleteAll<T>(IEnumerable<T> entities) where T : class
{
_dc.GetTable<T>().DeleteAllOnSubmit(entities);
_dc.SubmitChanges();
}
public void Dispose()
{
_dc.Dispose();
}
private Expression<Func<T, bool>> BuildWhereClause<T>(object id) where T : class
{
var parameter = Expression.Parameter(typeof(T));
var whereExpression = Expression.Lambda<Func<T, bool>>
(
Expression.Equal(Expression
.Property(parameter
, GetPrimaryKeyName<T>())
, Expression.Constant(id))
, new[] { parameter }
);
return whereExpression;
}
private string GetPrimaryKeyName<T>()
{
var primaryKey = _dc.Mapping
.GetMetaType(typeof(T))
.DataMembers
.SingleOrDefault(m => m.IsPrimaryKey);
if (primaryKey == null)
throw new MissingPrimaryKeyException();
return primaryKey.Name;
}
protected abstract DataContext DataContext { get; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment