I am new to Entity Framwrok.
I have this pattern so far.
1- IRepository
Here is the class
public interface IRepository<T> where T : BaseEntity
{
IEnumerable<T> GetAll();
T Get(long id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
}
2- Repository class :
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private readonly DBContext context;
private readonly IUnitOfWork unitOfWork;
private DbSet<T> entities;
public Repository(DBContext context, IUnitOfWork unitOfWork)
{
this.context = context;
this.unitOfWork = unitOfWork;
entities = context.Set<T>();
}
public IEnumerable<T> GetAll()
{
return entities.AsEnumerable();
}
public T Get(long id)
{
return entities.SingleOrDefault(s => s.ID == id);
}
public void Insert(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
entities.Add(entity);
unitOfWork.Complete();
}
public void Update(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
unitOfWork.Complete();
}
public void Delete(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
entities.Remove(entity);
unitOfWork.Complete();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
throw new NotImplementedException();
}
3- IUnitOfWork
public interface IUnitOfWork
{
void Complete();
void Dispose();
}
4- UnitOfWork
public class UnitOfWork : IUnitOfWork, IDisposable
{
readonly DBContext _dbContext;
public IRepositoryEmployeeBank EmployeeBank { get; set; }
public UnitOfWork(DBContext dbContext)
{
_dbContext = dbContext;
EmployeeBank = new RepositoryEmployeeBank(dbContext);
}
public void Complete()
{
_dbContext.SaveChanges();
}
public void Dispose()
{
_dbContext.Dispose();
}
}
Let us say we have an entity in our app called EmployeeBank
What I added
5- IRepositoryEmployeeBank
public interface IRepositoryEmployeeBank
{
}
6- RepositoryEmployeeBank
public class RepositoryEmployeeBank : IRepositoryEmployeeBank
{
public RepositoryEmployeeBank( DbContext dbContext)
{
DbContext = dbContext;
}
public DbContext DbContext { get; }
}
Now let us say we have an api controller called EmployeeBankController
How do I implement GetALl Methods ?
public class EmployeeBankController : Controller
{
public IUnitOfWork unitOfWork { get; set; }
public EmployeeBankController(IUnitOfWork _unitOfWork)
{
unitOfWork = _unitOfWork;
}
[Route("[action]")]
[HttpGet]
public List<dynamic> List()
{
List<dynamic> model = new List<dynamic>();
unitOfWork.// ForEach(a =>
{
var EmployeeBank = new
{
ID = a.ID,
Name = a.Name,
Active = a.IsActive,
IbanNumber = a.IBAN
};
model.Add(EmployeeBank);
});
return model.ToList();
}
}