sql to LINQ query

Anjali Agarwal 1,531 Reputation points
2023-05-08T00:21:07.11+00:00

I am trying to write this query in LINQ. This query returns a list:

SELECT TOP 500 sst.Id

, sst.status

, sst.Created

, sst.StatusChangeDate

, sstcnt.numitemid

, ssti.XML

FROM dbo.Transaction sst

  JOIN ( SELECT transactionid, COUNT(itemid) numitemid
     FROM dbo.TransactionItem ssti

	 GROUP BY ssti.TransactionId

	) sstcnt

ON sstcnt.TransactionId = sst.TransactionId

  JOIN dbo.TransactionItem ssti ON ssti.TransactionId = sst.TransactionId

ORDER BY sst.Created desc

any help will be appreciated.

SQL Server Other
Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-05-08T02:58:37.6933333+00:00

    Hi @Anjali Agarwal , Welcome to Microsoft Q&A.

    Its corresponding Linq is as follows:(Modify it according to your needs)

    using (var db = new MyDbContext())
    {
        var result = (
            from sst in db.Transaction
            join sstcnt in (
                from ssti in db.TransactionItem
                group ssti by ssti.TransactionId into g
                select new { TransactionId = g.Key, NumItemId = g.Count() }
            ) on sst.TransactionId equals sstcnt.TransactionId
            join ssti in db.TransactionItem on sst.TransactionId equals ssti.TransactionId
            orderby sst.Created descending
            select new object[]
            {
                            sst.Id,
                            sst.Status,
                            sst.Created,
                            sst.StatusChangeDate,
                            sstcnt.NumItemId,
                            ssti.XML
            }
        ).Take(500).ToList();
    }
    

    enter image description here

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.