MVC_part2
MVC_part2
Do not Repeat Yourself(DRY) -> 善用「泛型」的特性
1.create IRepository
2.Inheritance IRespository , then remove inside code
3.create GenericRespository
namespace MVCProject.Models.Repository
{
public class GenericRepository<TEntity> : IRepository<TEntity>
where TEntity : class
{
public void Create(TEntity instance)
{
throw new NotImplementedException();
}
public void Update(TEntity instance)
{
throw new NotImplementedException();
}
public void Delete(TEntity instance)
{
throw new NotImplementedException();
}
public TEntity Get( int primaryID)
{
throw new NotImplementedException();
}
public IQueryable<TEntity> GetAll()
{
throw new NotImplementedException();
}
public void SaveChanges()
{
throw new NotImplementedException();
}
public void Dispose()
{
throw new NotImplementedException();
}
}
}
4. fix IRepository -> because their function Get are different class
5. instance GenericRepository ,then delete ICompanyRepository and CompanyReposity
private DbContext _context { get; set; }
public GenericRepository()
{
this._context = new HoEntities();
}
public GenericRepository(DbContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
this._context = context;
}
public GenericRepository(ObjectContext context)
{
if (context==null)
{
throw new ArgumentNullException("context");
}
this._context = new DbContext(context, true);
}
public void Create(TEntity instance)
{
if (instance ==null)
{
throw new ArgumentNullException("instance");
}
else
{
this._context.Set<TEntity>().Add(instance);
this.SaveChanges();
}
}
public void Update(TEntity instance)
{
if (instance==null)
{
throw new ArgumentNullException("instance");
}
else
{
this._context.Entry(instance).State = EntityState.Modified;
this.SaveChanges();
}
}
public void Delete(TEntity instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance");
}
else
{
this._context.Entry(instance).State = EntityState.Deleted;
this.SaveChanges();
}
}
public TEntity Get(Expression<Func<TEntity,bool>> predicate)
{
return this._context.Set<TEntity>().FirstOrDefault(predicate);
}
public IQueryable<TEntity> GetAll()
{
return this._context.Set<TEntity>().AsQueryable();
}
public void SaveChanges()
{
this._context.SaveChanges();
}
protected virtual void Dispose(bool Disposing)
{
if (Disposing)
{
if (this._context != null)
{
this._context.Dispose();
this._context = null;
}
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
6.fix controller
參考網址: mrkt