linq - 在 Entity Framework Core 中的两个存储库之间加入
问题描述
表 A
a_id (PK)
aid_code
aid_desc
a_id | aid_code | aid_desc
---- -------- --------
1301 | FN | FAN
1302 | PN | PAN
1303 | LN | LAN
-> 表 A 有一列主键。
表 B
b_id (PK)
b_enddate (PK)
a_id (PK)
b_dob
b_name
code (not mapped property)
-> 表 B 具有使用 3 列的复合主键。
b_id | b_endate | a_id | b_dob | b_name
---- --------- ---- ---------- ------
1 | 01/01/2020 | 1301 | 01/01/2017 | sam
1 | 10/02/2020 | 1302 | 02/01/2016 | ham
2 | 01/10/2022 | 1303 | 03/01/2016 | jam
3 | 11/10/2023 | 1302 | 05/01/2015 | bam
有一个通用存储库,它只处理每个表 A 和表 B 的一个实体类。
var a = context.GetRepository<A>();
var b = context.GetRepository<B>();
消费者将以这种方式调用 API:{apiroute}/?id=1&code=FN
我必须按 id 过滤,它是 TableB 中的 b_id 列值和代码,它是表 A 中的aid_code 列值,但 TableB 只有表 A 中的 a_id 列值。
我在表 B 实体中添加了额外的未映射属性Code
以保存表 A 中的aid_code 的值,并在实体 API 和实体 B 之间进行了连接。我正在使用创建动态对象select new EntityB{ code = entityA.aid_code, ..... }
var records = from a in entityA
join b in entityB on b.a_id equals a.a_id
select new EntityB{ b_id = b.b_id, b_enddate = b.b_enddate, code = entityA.aid_code, ..... }
返回类型必须IQueryable<EntityB>
像我ToList()
稍后所做的那样。
我必须通过准备一个连接的 where 子句来完成过滤,但 where 子句的过滤不起作用。它在表 A 和 B 之间进行连接,而忽略了永远运行的 where 子句。
我究竟做错了什么?
解决方案
全部,我使用包含解决了这个问题,而不是执行连接并返回动态对象。首先,我在 DBContext 中的实体之间添加了一对多关系(因为我使用的是 EntityFrameworkCore),如下所示:
//这是EntityA的modelBuilder
entity.HasMany(m => m.EntityB)
.WithOne(c => c.EnitityA)
.HasForeignKey(k => k.a_id );
在 EntityB 中添加相应的导航属性,如下所示:
public virtual EntityA EntityA { get; set; }
同样,在 EntityA 中添加相应的导航属性,如下所示:
public virtual ICollection<EntityB> EntityB { get; set; }
然后最后包括:
var query = repoB.GetAll().Include("EntityA").AsNoTracking() as IQueryable<EntityB>
然后在上面的查询中执行 where 子句:
var returnVal = query.Where(x => x.EntityB.aid_code == paramValue):
var result = returnVal.ToList();
推荐阅读
- json - 如何使用结构构建以下 JSON 对象
- javascript - Chrome 扩展中的“未捕获的语法错误:参数列表后缺少)”
- c++ - 关于 Ipopt 中的 Hessian 检查器,我缺少什么?
- ios - 制作 App Store 应用的自定义版本
- eclipse - 最近的 Eclipse 更新可能导致它停止运行
- r - 名称文档中的 z <- "names<-"(z, "[<-"(names(z), 3, "c2")) 行是如何读取的?
- javascript - && 被用作 if 语句?
- python - 检查用户是否在语音频道 discord.py
- javascript - 第二次单击时带有箭头的水平滚动跳过滚动位置
- javascript - 一个简单的实时人员计数器示例