繁体   English   中英

EF如何使用.include()和使用存储库模式查询更多实体

[英]EF How to query more entities with .include() and using repository pattern

我得到了以下要使用linq(lambda表达式)实体框架实现的sql语句。 这是SQL:

select *
from tbl_ExampleStoneCatalog 
join tbl_ExampleStoneCategory 
on tbl_ExampleStoneCatalog.fk_ESC = tbl_ExampleStoneCategory.pk_ESC 
join tbl_ExampleStones
on tbl_ExampleStoneCatalog.fk_ES = tbl_ExampleStones.pk_ES
join tbl_ExampleReviewStoneCatalog 
on tbl_ExampleStones.pk_ES = tbl_ExampleReviewStoneCatalog.fk_ES
where .fk_StoneCategory = '%someParameter%'

我试图使用.include()来使我明白这一点:

var res = (await this._exampleStoneCatalog.Query()
          .include(esc => esc.ExampleStoneCategory)
          .include(es => es.ExampleStones)
          .include(es => es.ExampleStones.ExampleReviewStoneCatalog))
          .Where(w => w.ExampleStones.ExampleReviewStoneCatalog.Any(
           a => a.StoneCategoryID.Equals(%someParameter%)));

不幸的是,上述代码无法为我提供理想的结果。 此外,其中还有一个嵌套的Where条件=> ExampleStones.ExampleReviewStoneCatalog.StoneCategoryID 据我研究后了解到,使用.include()很难解决。

还有其他方法可以使用lambda表达式过滤嵌套查询吗?

如果似乎是多对多的关系。 我总是觉得从这里的连接表开始是最容易的。

var res = _tbl_B.Repository.Where(b => b.c.Value == "whatever" && b.a.Value == "whatever").Select(b => b.a);

我已经找到解决此问题的方法。 这里的主要挑战是过滤嵌套的SQL查询。 我无法使用.include()找到解决方案。 尤其是我当前使用存储库模式的工作环境不允许我在以下内容中进行过滤:

var res = await this._exampleStoneCatalog.Query().include(x => x.ExampleStones.ExampleReviewStoneCatalog.Where(w => w.StoneCategoryID.Equals(%SomeParameter%))).SelectAsync();

因此,我使用linq到sql来解决以下问题。

我的解决方案:

 var exampleStoneCatalogEnum = await this._exampleStoneCatalog.Query().SelectAsync();
 var exampleStoneCategoryEnum = await this._exampleStoneCategoryRepository.Query().SelectAsync();
 var exampleStonesEnum = await this.exampleStonesRepository.Query().SelectAsync();
 var exampleReviewStoneCatalogEnum = await this.exampleReviewStoneCatalogRepository.Query().SelectAsync();

 var result = from exampleStoneCatalog in exampleStoneCatalogEnum
              join exampleStoneCategory in exampleStoneCategoryEnum on exampleStoneCatalog.Id equals exampleStoneCategory.Id
              join exampleStones in exampleStonesEnum on exampleStoneCatalog.Id equals exampleStones.Id
              join exampleReviewStoneCatalog in exampleReviewStoneCatalogEnum on exampleStones.Id equals exampleReviewStoneCatalog.Id
              where exampleReviewStoneCatalog.StoneCategoryID.Equals(revCategory)
              select exampleStoneCatalog;
 return result;

如您所见,我首先获取每个表的必需数据,然后将它们加入到我的结果中,包括最后的where条件。 这将返回所需的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM