Tutorial :How do you return certain properties from a linq query, rather than complete objects?



Question:

I've just downloaded the Linq provider for NHibernate and am just a little excited. But I don't know Linq syntax that well.

I can return whole objects from a query like this:

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>()                    where foo.CaseNumber > 0                    select foo;  

And I can select a single property like this:

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>()                    where foo.CaseNumber > 0                    select foo.Id;  

But how would I select two properties, e.g. foo.Id and foo.Bar? Or is that not possible?

Thanks

David


Solution:1

Use an anonymous projection:

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>()                 where foo.CaseNumber > 0                 select new { foo.Id, foo.Bar };   


Solution:2

You have to create a new Anonymous type, that will only be available in the current scope (i.e. it can't be returned from a method etc.)

var query = from foo in session.Linq<Kctc.BusinessLayer.Domain.Case>()                 where foo.CaseNumber > 0                 select new { foo.Id, foo.Bar };   

Or you can create a custom class and populate that.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »