V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yuhangch
V2EX  ›  .NET

EF Core/ Postgresql LINQ 查询问题

  •  
  •   yuhangch · 2022-03-19 23:18:18 +08:00 · 2008 次点击
    这是一个创建于 762 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码示例:

    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 友给讲讲为什么,迷惑了半天不知道怎么查资料

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

    }
    ```
    thinkershare
        4
    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
        5
    yuhangch  
    OP
       2022-03-20 19:48:40 +08:00
    @thinkershare 是,哈哈,我一般也不这么写,主要写这个实例,不用 GetX 就和 X 重名了,显得有些怪
    yuhangch
        6
    yuhangch  
    OP
       2022-03-20 19:57:21 +08:00
    @thinkershare
    感谢👍,由于是接触 ef core 没多久,之前一直是直接加载,没用过 Include, include 之后确实可以了
    ```
    dbContext
    .Include(c => c.Point)
    .Select(
    s => new
    {
    Point = s.GetPoint(),
    });
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2959 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:11 · PVG 22:11 · LAX 07:11 · JFK 10:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.