1

I have SQL query:

WITH OrderedRecs AS
(select ROW_NUMBER() OVER(ORDER BY RecID) as seqNumber,* from Records where RecordGroupID=7)
SELECT * FROM OrderedRecs where RecordID=35

How do I get the same result using entity framework?

4
  • Do you mean where seqNumber=35? Commented Oct 25, 2011 at 16:57
  • No, I need record with specific ID, but with sequential number which is obtained by sorting all the records in any order Commented Oct 26, 2011 at 14:47
  • and instead of RecordID=35 may be more complicated condition Commented Oct 26, 2011 at 14:48
  • OK. So RecordID is a field in Records. The seqNumber will only number the records that satisfy RecordGroupID=x, so the row number will depend on that condition, is that OK? Commented Oct 26, 2011 at 17:00

2 Answers 2

1

A pure LINQ solution would be:

records.Where(rec => rec.RecordGroupID == 7)
    .OrderBy(rec => rec.RecId).AsEnumerable()
    .Select((rec, i) => new { i, rec })
    .Where(anon => anon.i == 35)
    .Select(anon => anon.rec).First()

But than you must be happy with the fact that all records matching the first condition are fetched locally.

Edit:

After you comments: Propably something like:

IEnumerable<SortedRecord> GetSortedRecords(IQueryable<Record> records
    , Func<SortedRecord, bool> sortedRecordPredicate)
{
    return
      records.Where(rec => rec.RecordGroupID == 7)
        .OrderBy(rec => rec.RecId).AsEnumerable()
        .Select((rec, i) => new SortedRecord{ Sequence = i, Record = rec })
        .Where(sortedRecordPredicate);
}

var result = GetSortedRecords(records, rec => rec.Record.RecordID = 35);

Where SortedRecord, obviously, is a type now, which enables you to enter all kinds of conditions. (syntax not checked).

A completely different approach would be to make a view of the query within the WITH clause.

Sign up to request clarification or add additional context in comments.

Comments

0

Couldn't you add SeqNumber as a derived (or discriminator) column to the base entity? See previous example. You would have to assign it yourself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.