使用实体框架的存储库模式(C)
存储库接口;
public interface IRepository<T>
{
void Insert(T entity);
void Insert(ICollection<T> entities);
void Delete(T entity);
void Delete(ICollection<T> entity);
IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
IQueryable<T> GetAll();
T GetById(int id);
}
通用存储库;
public class Repository<T> : IRepository<T> where T : class
{
protected DbSet<T> DbSet;
public Repository(DbContext dataContext)
{
DbSet = dataContext.Set<T>();
}
public void Insert(T entity)
{
DbSet.Add(entity);
}
public void Insert(ICollection<T> entities)
{
DbSet.AddRange(entities);
}
public void Delete(T entity)
{
DbSet.Remove(entity);
}
public void Delete(ICollection<T> entities)
{
DbSet.RemoveRange(entities);
}
public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public IQueryable<T> GetAll()
{
return DbSet;
}
public T GetById(int id)
{
return DbSet.Find(id);
}
}
使用演示酒店类的示例使用;
var db = new DatabaseContext();
var hotelRepo = new Repository<Hotel>(db);
var hotel = new Hotel("Hotel 1", "42 Wallaby Way, Sydney");
hotelRepo.Insert(hotel);
db.SaveChanges();