tags:

views:

46

answers:

2

When using linqtosql, and inner joining, can you return only a subset of columns or does it pull in all the column/properties?

Sometimes you need just 2-3 columns, having it pull back all 15 etc. seems like overkill.

+3  A: 

sure

var query =
  from c in db.Customers
  join o in db.Orders on c.CustomerID equals o.CustomerID
  select new {c.Name, o.OrderDate};
David B
A: 

That's what projections (anonymous types are for). You simply have to do:

from p in People
select new { p.Name, p.Age }

With a join it is possible to still use anonymous types. If you want to represent the one-to-many relationship, you simply do:

var query =
  from c in db.Customers
  join o in db.Orders on c.CustomerID equals o.CustomerID into g
  select new {c.Name, Orders = g };

However, this has the result of causing you to execute a new query to the database the first time the Orders are accessed for a customer.

If you simply want to flatten the structure, remove the grouping, and then just project into the new anonymous type, like others have suggested:

var query =
  from c in db.Customers
  join o in db.Orders on c.CustomerID equals o.CustomerID
  select new {c.Name, o.OrderDate};
casperOne
"remove the join"?
David B
can you do something similiar with nhibernate?
Blankman
@David B: Thanks for the catch, edited to reflect.
casperOne
@Blankman: I'm not that familiar with NHibernate, so I can't say for sure.
casperOne