Skip to content

Instantly share code, notes, and snippets.

@lucamilan
Forked from derans/l2s_repository.cs
Created April 4, 2012 18:45
Show Gist options
  • Save lucamilan/2304649 to your computer and use it in GitHub Desktop.
Save lucamilan/2304649 to your computer and use it in GitHub Desktop.
L2S Repository
public class LinqToSqlRepository<TContext>
: IDisposable where TContext : DataContext, new()
{
private readonly DataContext _dc;
public LinqToSqlRepository()
{
_dc = new TContext();
}
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment