Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write this cross apply query in LINQ-to-SQL?

Tags:

I have the following tables:

create table TableA (     Id int primary key identity,     Key int not null )  create table TableB (     Id int primary key identity,     TableA_Id int not null foreign key references TableA(Id),     Value varchar(80) not null ) 

I would like to write the following query in LINQ-to-SQL using lambda notation:

select TableA.Key, b.Value from TableA cross apply (     select top 10 TableB.Value     from TableB     where TableA.Id = TableB.TableA_Id     order by TableB.Value ) b where TableA.Key between 0 and 999 

How would I do this?

like image 251
cm007 Avatar asked Mar 20 '12 13:03

cm007


People also ask

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

What is the cross apply in SQL?

The CROSS APPLY operator is semantically similar to INNER JOIN. It retrieves all the records from the table where there are corresponding matching rows in the output returned by the table valued function.

How do you write a query in LINQ?

This query returns two groups based on the first letter of the word. List<int> numbers = new() { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; // The query variables can also be implicitly typed by using var // Query #1. IEnumerable<int> filteringQuery = from num in numbers where num < 3 || num > 7 select num; // Query #2.


2 Answers

This should do the trick

var query = from a in context.TableA             from b in context.TableB                              .Where(x => x.TableA_Id == a.Id)                              .OrderBy(x => x.Value)                              .Take(10)             where a.Key >= 0 && a.Key <= 999             select new             {               a.Key,               b.Value,             }; 
like image 130
Aducci Avatar answered Oct 02 '22 00:10

Aducci


//get latest activity info for every user

 var query = ActivityRepository.Where(p => p.iAction > -1 &&      userIds.Contains(p.iSellerId)).GroupBy(c => c.iSellerId).Select(c => c.OrderByDescending(cc => cc.dBeginTime).First()).Select(a => new ActivityInfo          {             ActivityId = a.iActivityId,             StartTime = a.dBeginTime,             SellerId = a.iSellerId,             EndTime = a.dEndTime,             ActivityName = a.sName,         }); 

this code will generate outer apply sytax.

like image 34
adu Avatar answered Oct 02 '22 01:10

adu