【问题标题】:How to use .Select to achieve .ThenInclude?如何使用.Select来实现.ThenInclude?
【发布时间】:2019-05-20 06:48:49
【问题描述】:

我想读取相关数据,但只读取特定字段。 如果使用包含 theninclude 将读取所有字段。 所以我使用.Select,但是如何使用.Select来实现.ThenInclude? 谢谢~

var ViewModel = await _context.A_Table
                .Select(s => new ViewModel {
                    A_TableId = s.Id,
                    B_Table = s.B_Table,
                    C_Table = ??? (s.B_Table.C_Table is wrong)
                });
public class A_Table
    {
        public int Id { get; set; }
        public string Field1 { get; set; }
        public IList<B_Table> B_Table { get; set; }
    }

public class B_Table
    {
        public int Id { get; set; }
        public string Field1 { get; set; }
        public int A_TableId { get; set; }
        public int C_TableId { get; set; }
        public C_Table C_Table { get; set; }
    }

public class C_Table
    {
        public int Id { get; set; }
        public string Field1 { get; set; }
        public B_Table B_Table { get; set; }
    }

【问题讨论】:

  • (s.B_Table.C_Table is wrong) 为什么会出错?你想读什么领域? s.B_Table.C_Table.Field1 怎么不适合你?

标签: c# .net-core entity-framework-core


【解决方案1】:

这是因为B_Table 属性是B_Table 的列表,所以当您想要访问其中的C_Table 属性时,您必须指定要访问列表中的哪个项目

例如 s.B_Table[0].C_Table 访问列表中的第一项。

如果你想聚合列表中的所有项目,你可以使用SelectMany using Linq inside namespace System.Linq

例如 s.B_Table.SelectMany(B_Table =&gt; B_Table.C_Table).ToList()

【讨论】:

    猜你喜欢
    • 2021-11-29
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 2018-09-15
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多