【问题标题】:Join between two repositories in Entity Framework Core在 Entity Framework Core 中的两个存储库之间加入
【发布时间】: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&amp;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&lt;EntityB&gt;,因为我稍后会使用ToList()

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

我做错了什么?

【问题讨论】:

  • 你没有向我们展示过滤,所以我们不能告诉你你做错了什么。
  • @Nemesis List&lt;T&gt; 没有实现IQueryable,你的意思是不是IEnumerableIQueryable 准备 sql 在数据库集合/表上执行。 IEnumerable 公开了保存在内存中的集合的枚举器。您确定需要返回 IQueryable 吗?
  • 是的,我必须返回 IQueryable 并将其传递给另一个方法,根据用户传入的查询参数(可能不止一个)通过 where 子句进行过滤。
  • @Nemesis 好的,这很公平。您的声明“返回类型必须是 IQueryable&lt;EntityB&gt;,因为我稍后会这样做 ToList()”,这并没有真正的意义。
  • 所有,我使用包含解决了这个问题。首先,我添加了 DBContext 中实体之间的一对多关系(因为我使用的是 EntityFrameworkCore),如下所示: entity.HasMany(m => m.EntityA) .WithOne(c => c.EnitityB) .HasForeignKey (k => k.a_id);

标签: linq entity-framework-core repository-pattern


【解决方案1】:

所有,我使用包含解决了这个问题,而不是执行连接并返回动态对象。 首先,我在 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();

【讨论】:

  • 您可以接受自己的答案,以表明问题已解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
  • 2021-10-11
相关资源
最近更新 更多