【问题标题】:Project into a (list of) concrete object instead of an (list of) anonymous object投影到(列表)具体对象而不是(列表)匿名对象
【发布时间】:2017-11-14 08:10:38
【问题描述】:

问题简化如下:在实体框架中,我正在做一个涉及 3 个表的连接,并返回连接的结果集,其中涉及 3 个表中的(一些)字段。

var query = (
        from t1 in dbCtx.TB_Entity1
        from t2 in dbCtx.TB_Entity2
             .Where(p => p.someCol  == t1.someCol && t.IsActive == true)
             .DefaultIfEmpty() //LEFT JOIN
        from t3 in dbCtx.TB_Entity3
             .Where(q => q.someCol == t2.someCol)
        where t1.IsLatest == true
        && (t1.istatus == 2 
            || t1.istatus == 3 
        )
        select new {
            t1.col100,
            t1.col101,
            t2.col200,
            t2.col201,
            t3.col300,
            t3.col301
        }).OrderByDescending(t1 => t1.ID);

var anonObjList = query.ToList();

因此,在查询结束时,我编写了一个投影来选择我想要的字段。

最后我使用 .ToList() 运行查询并获得匿名对象列表。

如何修改查询以投影到 MyConcreteClass 列表中

即我希望能够写出类似的东西

List<MyConcreteClass> myObjList = query.ToList();

你可以假设我的具体类看起来像

public class MyConcreteClass
{
    public string Col100 { get; set; }
    public string Col101 { get; set; }
    public string Col200 { get; set; }
    public string Col201 { get; set; }
    public string Col300 { get; set; }
    public string Col301 { get; set; }
}

【问题讨论】:

    标签: entity-framework linq projection


    【解决方案1】:

    您只需使用对象初始化语法:

    new MyConcreteClass
    {
        Col100 = t1.col100,
        Col101 = t1.col101,
        Col200 = t2.col200,
        Col201 = t2.col201,
        Col300 = t3.col300,
        Col301 = t3.col301
    }
    

    【讨论】:

    • 如何/在哪里?你能按照原意重新编写查询吗?
    • @joedotnot just write it instead of the new { ... } part in the select
    • 接受!它有效:-) 我认为需要一些复杂的 lambda 语法选择(z=> 等等)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    相关资源
    最近更新 更多