JL.
JL.

Reputation: 81262

How do you include all fields from first table in join, and some from remaining?

Given the following:

var item = (from table1 in Entity.table1
                            join table2 in Entity.table2
                            on table1.ID equals table2.fkId
                            where table1.ID == TheID
select table1
)

How can I return all the fields from table1, and then add a few from table2 without having to explicitly define all the columns again like this:

where table1.ID == TheID
   select new
      {
         table1.field,
         table1.field2,
         etc, etc,etc,etc,
         table2.field1

      }

Upvotes: 3

Views: 54

Answers (2)

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

You can keep both table1, and table2 instead

where table1.ID == TheID
select new
  {
     table1,
     table2

  }

and access to the fields of this anonymous class by by myItem.table1.field

If however you want to access by first-level properties, you can create dynamic class, that returns proper value by reflection from one or another table, or implement ICustomTypeDescriptor interface if you want to show table on UI(both Winform and WPF grids recognize this interface)

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

How can I return all the fields from table1, and then add a few from table2 without having to explicitly define all the columns

You can't. All properties of anonymous object should be specified. But you can return whole instance from table1 and some fields from table2:

  select new
  {
     table1
     table2.field1
  }

Then all properties from first table will be available via x.table1.field2 and you would not list them all manually.

Upvotes: 1

Related Questions