【问题标题】:How to add include in Generic repository pattern in Ef Core?如何在 Ef Core 的通用存储库模式中添加包含?
【发布时间】:2020-09-28 17:06:02
【问题描述】:

Net core 和 efcore db 第一种方法。我有两张桌子。第一个表是 SiteDetails,它包含与 Sitedetails 相关的列,它根据主键和外键关系引用其他表国家。现在我想将这些国家也包括在内作为结果的一部分。下面是我的通用方法。

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

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

【问题讨论】:

    标签: c# .net-core ef-core-2.0 db-first


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢。这就是我需要的。另外,如果我想要 orderby 那么 x=>x.feildname 我需要发送正确
    猜你喜欢
    • 2020-11-10
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多