如何在 Entity Framework 核心 1.0.1 原始查询中包含相关实体?

How to include related entities in an Entity Framework Core 1.0.1 raw query?

设置:

上下文:MainContext (maindb)、Module1Context (module1db)、Module2Context (module2db)。

我想执行 returns Post 列表(来自 Module1Context)的查询,但我需要按作者权限(来自 MainContext,用户实体)过滤它们。

所以,我想做的是使用 JOIN 子句对不同的数据库执行查询 table:

var results = await module1Ctx.Posts.FromSql("select * from `module1db`.`posts` as `p` inner join `maindb`.`users` as `u` on `p`.`AuthorId`=`u`.`Id` where <conditions here>").ToListAsync();

执行时,我得到一个 SQL 异常告诉我 "Sequence contains more than one element"。如果我select p.*,就可以了,但是我还需要拉取用户数据。

Post 实体包含对用户 ID 的引用(public 长 AuthorId {get;set;}),以及假导航 属性,NotMapped,因为 EF 无法' 自动加入 2 个数据库。 我的第一个问题是——这可能吗?我有一种强烈的感觉,这会奏效,但我遗漏了一些小东西。

如果这不起作用,我将求助于使用 DbContext 的连接手动执行查询。如果我这样做,我如何将结果映射到 Post 的列表中,包括用户数据?

Sequence contains more than one element

这告诉您某个列出现了不止一次。例如,如果您在两个 table 中都有“ModifiedDate”列,当您执行 select * 时,它将在结果集中出现两次(一次 p.ModifiedDate,一次在 u.ModifiedDate

除此之外,列 returned 必须与模型完全匹配。不能缺少模型中定义的 属性,这就是 p.* 起作用的原因。

但是除非您的 Post 模型确实定义了表示来自 User table 的值的字段,否则您不能 return 它们,因为它必须完全匹配 Post 和它的映射属性。

临时支持(将结果映射到任意模型,如视图模型)尚未在 EntityFramework Core 1.0 中实现,并且是 roadmap for future versions.[=22= 的一项功能]

来自 EntityFramework 核心路线图:

Critical O/RM features

  • ...
  • Raw SQL queries for non-Model types allows a raw SQL query to be used to populate types that are not part of the model (typically for denormalized view-model data).

编辑

也来自EFCore documentation

Limitations

There are a couple of limitations to be aware of when using raw SQL queries:

  • SQL queries can only be used to return entity types that are part of your model. There is an enhancement on our backlog to enable returning ad-hoc types from raw SQL queries.
  • The SQL query must return data for all properties of the entity type.
  • The column names in the result set must match the column names that properties are mapped to. Note this is different from EF6.x where property/column mapping was ignored for raw SQL queries and result set column names had to match the property names.
  • The SQL query cannot contain related data. However, in many cases you can compose on top of the query using the Include operator to return related data (see Including related data).