Generic Entity Framework 4.0 Base Repository
时间:2010-08-31 来源:jes.shaw
代码
public interface IRepository<T> where T : class
{
IQueryable<T> GetQuery();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> where);
T Single(Expression<Func<T, bool>> where);
void Delete(T entity);
void Add(T entity);
}
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
readonly IObjectContext _objectContext = null;
readonly IObjectSet<TEntity> _objectSet = null;
public BaseRepository(IObjectContext objectContext)
{
if (objectContext == null)
throw new ArgumentNullException("objectContext");
_objectContext = objectContext;
_objectSet = _objectContext.CreateObjectSet<TEntity>();
}
public IQueryable<TEntity> GetQuery()
{
return _objectSet;
}
public IEnumerable<TEntity> GetAll()
{
return _objectSet.ToList();
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> where)
{
return _objectSet.Where(where);
}
public TEntity Single(Expression<Func<TEntity, bool>> where)
{
return _objectSet.SingleOrDefault(where);
}
public void Delete(TEntity entity)
{
_objectSet.DeleteObject(entity);
}
public void Add(TEntity entity)
{
_objectSet.AddObject(entity);
}
}
{
IQueryable<T> GetQuery();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> where);
T Single(Expression<Func<T, bool>> where);
void Delete(T entity);
void Add(T entity);
}
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
readonly IObjectContext _objectContext = null;
readonly IObjectSet<TEntity> _objectSet = null;
public BaseRepository(IObjectContext objectContext)
{
if (objectContext == null)
throw new ArgumentNullException("objectContext");
_objectContext = objectContext;
_objectSet = _objectContext.CreateObjectSet<TEntity>();
}
public IQueryable<TEntity> GetQuery()
{
return _objectSet;
}
public IEnumerable<TEntity> GetAll()
{
return _objectSet.ToList();
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> where)
{
return _objectSet.Where(where);
}
public TEntity Single(Expression<Func<TEntity, bool>> where)
{
return _objectSet.SingleOrDefault(where);
}
public void Delete(TEntity entity)
{
_objectSet.DeleteObject(entity);
}
public void Add(TEntity entity)
{
_objectSet.AddObject(entity);
}
}
相关阅读 更多 +