加入LINQ可以避免在"new {}"中明确命名属性? [英] Join in LINQ that avoids explicitly naming properties in "new {}"?

查看:86
本文介绍了加入LINQ可以避免在"new {}"中明确命名属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

    DataTable q = from c in customers
            join o in orders on c.Key equals o.Key
            into outer
            from j in outer.DefaultIfEmpty()
            select new { c.*, j.* };

我最近得到的是以下内容:

The closest I currently got is the following:

    var q = from c in customers
            join o in orders on c.Key equals o.Key
            into outer
            from j in outer.DefaultIfEmpty()
            select new { c, j };

我希望我的结果(q)包含c和j的所有列. c和j都包含很多列,所以我宁愿不这样列出它们:

I'd like my result (q) to have all the columns from c and j. both c and j contain a lot of columns, so I'd rather not list them as such:

            select new { c.col1, c.col2, etc. }

但是我基本上希望最终的DataTable由c.*和j.*组成.

But I basically want the final DataTable to be made up of c.* and j.*.

如果我在'select new'中指定了所有c和j列,则此答案(不是接受的答案,但下面的答案)有效: 如何将LINQ结果转换为DATATABLE? 但我想避免全部列出.

This answer (not the accepted answer, but the one below it) works if I specify all the c and j columns inside 'select new': How to Convert a LINQ result to DATATABLE? But I'd like to avoid listing them all.

推荐答案

首先,我希望手动指定列,因为我想最小化基础层(数据库架构,查询提供程序)对我的应用程序的影响.但是,如果您真的想要执行此操作,则可以通过某种技巧来实现它.

First, I would prefer to specify the columns manually, because I would like to minimize the impact of underlying layers - database schema, query provider - on my application. But if you really want to do this there is a bit of a hacky way to accomplish it.

当您使用实体框架时(首先是数据库):

When your are using entity framework (database first):

var qs = ((ObjectQuery)q).ToTraceString();
var ds = new DataSet();
var da = new SqlDataAdapter(qs, new SqlConnection(((EntityConnection)context.Connection).StoreConnection.ConnectionString));
da.Fill(ds, "Result");

这个想法是在实际执行发出的SQL之前捕获它,并使用它填充DataTable(在DataSet中).

The idea is to catch the emitted SQL before it is actually executed and use it to fill a DataTable (in a DataSet).

与Linq-to-sql基本相同,只是获取命令字符串和连接字符串的方式不同:

With Linq-to-sql is is basically the same, just the way to get the command string and connection string is different:

context.GetCommand(q).CommandText
context.Connection.ConnectionString

以EF代码优先:

q.ToString()
context.Database.Connection.ConnectionString

这篇关于加入LINQ可以避免在"new {}"中明确命名属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆