EF Core/ Postgresql LINQ 查询问题

2022-03-19 23:18:18 +08:00
 yuhangch

代码示例:

https://gist.github.com/yuhangch/bca2774ee4ede011213731ecf761523b#file-ef-core-pg-command-is-already-in-progress-cs-L33

大致描述一下:

一个实体,有两个 field

public class Obj : IObj
{
    string Name 
    Point Point // 外键关联的 InverseProperty 
}

接口IobjObj 两个字段的 Getter

dbContext.Objs.Select(o => s.GetName()) // 能用
dbContext.Objs.Select(o => s.GetPoint()) // 不能用

第二个会报command is already in progress错误。

请 v 友给讲讲为什么,迷惑了半天不知道怎么查资料

2020 次点击
所在节点    .NET
6 条回复
madao1993
2022-03-19 23:40:53 +08:00
会不会和 LINQ 的 deferred evaluation 特性有关,select 得到的结果在被枚举之前不会执行
netnr
2022-03-20 07:07:18 +08:00
从数据库生成代码(Scaffold-DbContext),看看和你写的有没有区别
thinkershare
2022-03-20 15:26:04 +08:00
你的代码非常奇怪, 一般在 EF Core 中, 正常的写法是
```csharp
public class Entity: IIterface {

}
```
thinkershare
2022-03-20 15:31:52 +08:00
你的代码非常奇怪, 一般在 EF Core 中, 正常的写法是
public class Entity: IEntity{
public string Name{get;private set;}
public virtual Point{get;private set;}
}

很少使用 GetXxx 或者 SetXxx 的形式, 另外导航属性默认是懒加载的, 虽然你也可以将其调整为直接加载, 一般还是要手动 Include 的, 接口完全可以定义属性哈
yuhangch
2022-03-20 19:48:40 +08:00
@thinkershare 是,哈哈,我一般也不这么写,主要写这个实例,不用 GetX 就和 X 重名了,显得有些怪
yuhangch
2022-03-20 19:57:21 +08:00
@thinkershare
感谢👍,由于是接触 ef core 没多久,之前一直是直接加载,没用过 Include, include 之后确实可以了
```
dbContext
.Include(c => c.Point)
.Select(
s => new
{
Point = s.GetPoint(),
});
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/841550

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX