-
Notifications
You must be signed in to change notification settings - Fork 0
Parte 11
WILSON DE OLIVEIRA JUNIOR edited this page Mar 9, 2020
·
4 revisions
[Voltar]
Padrão "Repository", criando repositório genérico:
- No projeto Taste.Domain crie uma pasta chamada Interfaces.
- Na pasta Interfaces crie uma nova classe chamada IRepository.cs.
- O código dessa classe deve ser o seguinte:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Taste.Domain.Interfaces
{
public interface IRepository<T> where T : class
{
Task<T> Get(int id);
Task<IEnumerable<T>> GetAll(
Expression<Func<T, bool>> filter = null,
Func<IQueryable<T>, IOrderedEnumerable<T>> orderBy = null,
string includeProperties = null
);
Task<T> GetFirstOrDefault(
Expression<Func<T, bool>> filter = null,
string includeProperties = null
);
Task Add(T entity);
void Remove(T entity);
Task Remover(int id);
}
}- No projeto Taste.DataAccess crie uma nova pasta chamada *Repository.
- Nessa nova pasta Repository crie uma nova classe chamada RepositoryBase.
- Essa nova classe deve ter o seguinte código:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Taste.Domain.Interfaces;
namespace Taste.DataAccess.Repository
{
public class BaseRepository<T> : IRepository<T> where T : class
{
protected readonly DbContext Context;
internal DbSet<T> dbSet;
public BaseRepository(DbContext context)
{
Context = context;
this.dbSet = context.Set<T>();
}
public async Task Add(T entity)
{
await this.dbSet.AddAsync(entity);
}
public async Task<T> Get(int id)
{
return await this.dbSet.FindAsync(id);
}
public void Remove(T entity)
{
dbSet.Remove(entity);
}
public async Task Remover(int id)
{
T entityToRemove = await dbSet.FindAsync(id);
Remove(entityToRemove);
}
public async Task<IEnumerable<T>> GetAll(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedEnumerable<T>> orderBy = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
query = query.Where(filter);
if (!string.IsNullOrEmpty(includeProperties))
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
if (orderBy != null)
{
var q = orderBy(query);
return q.ToList();
}
return await query.ToListAsync();
}
public async Task<T> GetFirstOrDefault(Expression<Func<T, bool>> filter = null, string includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
query = query.Where(filter);
if (!string.IsNullOrEmpty(includeProperties))
{
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
}
return await query.FirstOrDefaultAsync();
}
}
}[Voltar]