【发布时间】:2020-04-26 10:38:48
【问题描述】:
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
我必须按表B中的b_id列值的id和表A中的aid_code列值的代码进行过滤,但表B只有表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 子句。
我做错了什么?
【问题讨论】:
-
你没有向我们展示过滤,所以我们不能告诉你你做错了什么。
-
@Nemesis
List<T>没有实现IQueryable,你的意思是不是IEnumerable?IQueryable准备 sql 在数据库集合/表上执行。IEnumerable公开了保存在内存中的集合的枚举器。您确定需要返回IQueryable吗? -
是的,我必须返回 IQueryable 并将其传递给另一个方法,根据用户传入的查询参数(可能不止一个)通过 where 子句进行过滤。
-
@Nemesis 好的,这很公平。您的声明“返回类型必须是
IQueryable<EntityB>,因为我稍后会这样做ToList()”,这并没有真正的意义。 -
所有,我使用包含解决了这个问题。首先,我添加了 DBContext 中实体之间的一对多关系(因为我使用的是 EntityFrameworkCore),如下所示: entity.HasMany(m => m.EntityA) .WithOne(c => c.EnitityB) .HasForeignKey (k => k.a_id);
标签: linq entity-framework-core repository-pattern