加入LINQ可以避免在"new {}"中明确命名属性?

编程入门 行业动态 更新时间:2024-10-25 22:27:29
本文介绍了加入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 {}"中明确命名属性?

本文发布于:2023-11-05 19:19:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561633.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   LINQ   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!