C# LINQ中如何隔离where子句实现多类型花卉数据查询逻辑复用
实现方案
第二个参数使用Expression<Func<ClientFirst, bool>>类型(表达式树),可以完美隔离不同的where过滤逻辑,同时保证EF能将过滤条件正确翻译为SQL,不会出现内存过滤的性能问题。
封装后的通用方法代码
using System.Linq.Expressions; // 需提前引入该命名空间 private IQueryable<FlowerDTO> GetFlowerData(Expression<Func<ClientFirst, bool>> filter) { return dbContext.ClientFirst .Where(filter) .Select(c => new FlowerDTO { flowerId = c.Id, flowerCatergory = c.flowerCatergory }); }
提示:flowerId参数可以直接写到调用时的过滤表达式里,不需要单独作为方法参数传入,灵活性更高。
调用示例
- 查询玫瑰花卉数据:
RoseFlowersData = GetFlowerData(c => c.RoseFlower.Id == Id);
- 查询紫菀花卉数据:
AsterFlowerData = GetFlowerData(c => c.AsterFlower.Id == Id);
后续新增其他花卉类型,只需要新增对应的调用语句,传入对应过滤表达式即可,不需要修改通用方法本身。
内容的提问来源于stack exchange,提问作者Maddy
相关产品推荐
相关产品推荐

