Join LINQ to avoid explicitly specifying properties in "new {}"?

I would like to do something like this:

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 got 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 }; 

I want my result (q) to have all columns from c and j. both c and j contain many columns, so I would prefer not to list them as such:

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

But I basically want the final DataTable to consist of c. * and j. *.

This answer (not the accepted answer, but below) works if I specify all columns c and j inside 'select new': How to convert LINQ result to DATATABLE? But I would like not to list them all.

+6
source share
2 answers

Firstly, I would prefer to specify the columns manually, because I would like to minimize the influence of the base layers - the database schema, the query provider - on my application. But if you really want to do this, there is a little hacky way to achieve this.

When you use the entity infrastructure (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"); 

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

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

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

With the first EF code:

 q.ToString() context.Database.Connection.ConnectionString 
+1
source

I think that this is impossible. You can do this only as you showed in the question: select new { c, j }; or by listing all columns.

There are many other threads in this:

0
source

Source: https://habr.com/ru/post/918686/


All Articles