vendredi 3 septembre 2021

ASP.NET CORE - How to create generic repository pattern with unit of work with Ado.net (No entity framework)

I am using ASP.NET Core, with a design pattern (generic repositories) with entity framework. The problem is entity framework does not have a sql_dependency, and I really want to use sql_dependency in my projects, Also I am using a design pattern with generic repositories.

I need a way to use Ado.net with a generic repository pattern with a unit of work

My Code ...

-- Repository Interface

 public interface IGRepository<T> where T : class
{
    IQueryable<T> GetAll();
    Task<T> GetByIdAsync(Object id);
    void Insert(T entity);
    void Update(T entity);
    void Delete(Object id);
}

-- Unit of work Interface

 public interface IUnitOfWork<T> where T : class
{
    IGRepository<T> Entity { get; }
    Task SaveAsync();
}

-- Generic repository

  public class GRepository<T> : IGRepository<T> where T : class
{
    private readonly DataContext _context;
    private DbSet<T> table = null;
    public GRepository(DataContext context)
    {
        _context = context;
        table = _context.Set<T>();
    }

    public async Task<T> GetByIdAsync(Object id)
    {
        return await table.FindAsync(id);
    }

    public void Delete(Object id)
    {
        T existing = table.Find(id);
        table.Remove(existing);
    }

    public IQueryable<T> GetAll()
    {
        return table.AsQueryable().AsNoTracking();
    }

    public void Insert(T entity)
    {
        table.Add(entity);
    }
    public void Update(T entity)
    {
        table.Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
    }

    //public IQueryable<T> Find(Expression<Func<T, bool>> predicate)
    //{
    //    return table.AsNoTracking().Where(predicate);
    //}

    //public IQueryable<T> Include(params Expression<Func<T, object>>[] includes)
    //{
    //    IQueryable<T> query = table;
    //    foreach (Expression<Func<T, object>> include in includes)
    //        query = query.Include(include);

    //    return query; // عندما تكون IQueryable لا تقبل query.ToList(); لأنها لأن نتيجتها هي ليست
    //}

    //public List<T> Get(Expression<Func<T, bool>> filter = null,
    //                     Func<IQueryable<T>,
    //                     IOrderedQueryable<T>> orderBy = null,
    //                     params Expression<Func<T,
    //                     object>>[] includes)
    //{

    //    IQueryable<T> query = table;

    //    foreach (Expression<Func<T, object>> include in includes)
    //        query = query.Include(include);

    //    if (filter != null)
    //        query = query.Where(filter);

    //    if (orderBy != null)
    //        query = orderBy(query);

    //    return query.ToList();
    //}
}
  • Please any help to change it to Ado.net (No entity framework)

Aucun commentaire:

Enregistrer un commentaire