views:

787

answers:

3

Hi, How can I do the following query in subsonic 2.2

select Table1.Id, Table1.Name, Table1.Age from Table1
where Table1.Id =
(
select Max(T.Id) from Table1 T
Where T.Age = 20
)

Can one can provide me with example.

Thanks. nRk

A: 

As far as I know there is no support for subqueries in SubSonic. You'll need to put the query in a sproc and use the generated SPs.SprocName() method.

EDIT: I was wrong, see other answer below.

John Sheehan
SubSonic 2.1+ can handle SubQueries
runxc1 Bret Ferrier
Since I have been proven wrong below, I will delete this answer, but it needs to be unaccepted first since you can't delete an accepted answer.
John Sheehan
+3  A: 

Subsonic 2.2 can do sub-queries:

As Adam suggested, editted and improved example using In, this works for me:

SubSonic.Select s = new SubSonic.Select(SSDAL.Customer.CustomerIDColumn, SSDAL.Customer.NameColumn);
SubSonic.Aggregate a = new SubSonic.Aggregate(SSDAL.Customer.CustomerIDColumn, SubSonic.AggregateFunction.Max);
SSDAL.CustomerCollection COL = new SSDAL.CustomerCollection();
SubSonic.Select sq = new SubSonic.Select("LastCustomerId");
sq.Aggregates.Add(a);
sq.From(Tables.Customer);
a.Alias = "LastCustomerId";
s.From(Tables.Customer);
s.Where(SSDAL.Customer.CustomerIDColumn).In(sq);
COL = s.ExecuteAsCollection<SSDAL.CustomerCollection>();
;

This code produces the following SQL:

SELECT [dbo].[Customer].[CustomerID], [dbo].[Customer].[Name]
 FROM [dbo].[Customer]
 WHERE [dbo].[Customer].[CustomerID] IN (SELECT MAX([dbo].[Customer].[CustomerID]) AS 'LastCustomerId'
 FROM [dbo].[Customer])
Zapatta
You want to use In rather than IsEqualTo though
Adam
Hi, Zapatta Thanks,I tried the same.. but it is giving error.. IsEqual is expecting a single value.. but query returning a collection.And one more thing is, the Select statment converted to two different quries..not as a subquery which is not expecting.Thank younrk
nRk
I have edited my original answer to include a sub-query sample that works for me and should work for you with some changes to suit. It uses In rather than IsEqualTo as suggested by Adam.
Zapatta
+1  A: 

Adam may be onto something but it looks a little ugly. Here is an example that is a bit more readable that returns an IDataReader

new SubSonic.Select(Table1.IdColumn,Table1.NameColumn,Table1.AgeColumn)
.From(Table1.Schema)
.Where(Table1.IdColumn).In(new SubSonic.Select(Aggregate.Max(Table1.IdColumn)).From(Table1.Schema))
.ExecuteReader();
runxc1 Bret Ferrier