GenericRepository
public interface IGenericRepository<TEntity> where TEntity : class { IQueryable<TEntity> GetAll(); IQueryable<TEntity> FindBy(Expression<Func<TEntity , bool>> predicate); void Add(TEntity entity); void Delete(TEntity entity); void Edit(TEntity entity); void Save(); }
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class { private readonly DbContext _context; private readonly IDbSet<TEntity> _entities; public GenericRepository(DbContext context) { this._context = context; _entities = _context.Set<TEntity>(); } public virtual IQueryable<TEntity> GetAll() { IQueryable<TEntity> query = _entities; return query; } public IQueryable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate) { IQueryable<TEntity> query = _entities.Where(predicate); return query; } public virtual void Add(TEntity entity) { _entities.Add(entity); } public virtual void Delete(TEntity entity) { _entities.Remove(entity); } public virtual void Edit(TEntity entity) { // entity.State = EntityState.Modified; } public virtual void Save() { //_entities.SaveChanges(); } }
public class MyContext : DbContext { public MyContext(){} public MyContext(string nameOrConnectionString) : base(nameOrConnectionString) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); //取消级联删除设置 modelBuilder.Entity<Area>().ToTable("Area"); base.OnModelCreating(modelBuilder); } public DbSet<Area> Area { get; set; } }
public class AreaRepository : IAreaRepository { private GenericRepository<Area> internalGenericRepository; public AreaRepository(GenericRepository<Area> internalGenericRepository) { this.internalGenericRepository = internalGenericRepository; } public List<Area> GetAllProvince() { var query = from o in this.internalGenericRepository.GetAll() //where o.AreaTypeID == AreaTypeEnum.Province select o; return query.ToList(); } }
public class AreaService : IAreaService { private readonly IAreaRepository _AreaRepository; public AreaService(IAreaRepository areaRepository) { this._AreaRepository = areaRepository; } public List<DictionaryEntry> ProvinceList { get { var query = from o in this._AreaRepository.GetAllProvince() select new DictionaryEntry(o.Name, o.Id); return query.ToList(); } } }
IUnityContainer container = new UnityContainer(); container.RegisterInstance<DbContext>(new MyContext("ConnectionString")); //注册实例 container.RegisterType<IAreaService, AreaService>(); container.RegisterType<IAreaRepository, AreaRepository>(); container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>)); var IAreaService = container.Resolve<IAreaService>(); //实例化接口 Console.WriteLine(IAreaService.ProvinceList.Count());
签名:删除冗余的代码最开心,找不到删除的代码最痛苦!