在 Entity Framework Core 中的两个存储库之间加入

Join between two repositories in Entity Framework Core

Table一个

a_id (PK) 
aid_code 
aid_desc

a_id |  aid_code |  aid_desc
----    --------    --------
1301 |  FN       |  FAN
1302 |  PN       |  PAN
1303 |  LN       |  LAN

-> Table A 有一个列主键。

Table B

b_id (PK)
b_enddate (PK)
a_id (PK)
b_dob
b_name
code (not mapped property)

-> Table 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

有一个通用存储库,它只处理每个 Table A 和 Table B 的一个实体 class。

var a = context.GetRepository<A>();
var b = context.GetRepository<B>();

消费者将这样调用 API:{apiroute}/?id=1&code=FN

我必须按 id 过滤,它是 TableB 中的 b_id 列值,以及 TableA 中的 aid_code 列值的代码,但 TableB 只有来自 Table A 的 a_id 列值。

我添加了额外的未映射 属性 says Code in Table B entity to hold the value for aid_code from Table A and did a join实体之间 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, ..... }

return 类型必须是 IQueryable<EntityB>,因为我稍后会做 ToList()

我必须通过准备一个串联的 where 子句来进行最后的过滤,但是按 where 子句进行的过滤不起作用。它在 Tables A 和 B 之间进行连接,忽略永远 运行 的 where 子句。

我做错了什么?

总而言之,我使用 include 解决了这个问题,而不是执行连接并返回动态对象。 首先,我在 DBContext 中添加了实体之间的一对多关系(因为我正在使用 EntityFrameworkCore),如下所示:

//这是 EntityA 的模型构建器

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