如何在 Ef Core 中添加包含在通用存储库模式中?

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

Net Core 和 efcore 数据库优先方法。我有两个 table。第一个 table 是 SiteDetails,它包含 Sitedetails 相关列,并根据主键和外键关系引用其他 table 个国家/地区。现在我想将这些国家也包括在结果中。下面是我的通用方法。

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);
        }

在下面的代码中我调用了上面的方法

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

下面是siteDetails页面Country之间的关系Table SitDetails 有字段 siteNo, siteName, CountryId 国家有字段 CountryId 和 CountryName

谁能帮我在这里写 include 语法。任何帮助,将不胜感激。谢谢

如果您想使用 GenericRepository,您应该在初始化时声明类型。如果您不使用显式类型(如 SiteDetail)初始化 GenericRepository,则在您的示例中这是 Initializing:

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

并且您可以使用定义的类型调用存储库方法:

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