Reputation: 903
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
Upvotes: 2
Views: 5175
Reputation: 53
public async Task<ICollection<TEntity>> GetAsync(
params Expression<Func<TEntity, object>>[] includes)
{
return await includes
.Aggregate(_dbContext.Set<TEntity>().AsQueryable(),
(entity, property) => entity.Include(property))
.ToListAsync();
}
Upvotes: 0
Reputation: 68
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);
Upvotes: 2