Search code examples
c#.net-coreef-core-2.0db-first

How to add include in Generic repository pattern in Ef Core?


Net core and efcore db first approach. I have two tables. First table is SiteDetails and it contains Sitedetails related columns and it references other table countries based on primary key and foreign key relationships. Now I want to include these countries also as part of result. Below is my generic method.

public async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, params Expression<Func<T, object>>[] includes)
        {
            IQueryable<T> query = this.dbSet;
            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 await query.ToListAsync().ConfigureAwait(false);
        }

In below code I am calling above method

 var siteDetails= await this.siteDetailsRepository.GetAsync(x => x.siteNo== siteNo , source => source.Include(???)).ConfigureAwait(false);

Below is the relationship between siteDetails page Country Table SitDetails has fields siteNo, siteName, CountryId Country has fields CountryId and CountryName

Can someone help me to write include syntax here. Any help would be appreciated. Thanks


Solution

  • When you want to use GenericRepository you should declare Type when Initializing. if you don't initilize GenericRepository with Explicit Type (like SiteDetail) this is Initializing in your example:

    public class SiteDetailService : ISiteService 
    {
        private readonly IBaseRepository<SiteDetail> _siteDetailRepository;
        public SiteDetailService(IBaseRepository<SiteDetail> siteDetailsRepository)
        {
            _siteDetailRepository = siteDetailsRepository;
        }
    }
    

    and you can call your repository methods with defined Type:

       var siteDetails = 
               await this._siteDetailsRepository
                         .GetAsync(x => 
                                   x.siteNo == siteNo,  //Conditions         
                                   null,                //Orders          
                                   x => x.Country)      //Includes
               .ConfigureAwait(false);