现在的位置: 首页 > 综合 > 正文

Generic Entity Framework 4.0 Base Repository

2013年01月28日 ⁄ 综合 ⁄ 共 1247字 ⁄ 字号 评论关闭
代码

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);
   }
}

 

抱歉!评论已关闭.