2

I have this code:

var wordForms = await db.WordForms
   .Where(w => w.Text == word)
   .AsNoTracking()
   .ToListAsync();

It returns a list but there's only ever one entry as Text is unique. How can I make this just retrieve one word only?

1
  • Can you modify ToListAsync to achieve the necessary result Commented May 27, 2016 at 8:01

4 Answers 4

4

use FirstOrDefaultAsync as your final LINQ method:

 var wordForms = await db.WordForms
                         .AsNoTracking()
                         .FirstOrDefaultAsync(w => w.Text == word)
Sign up to request clarification or add additional context in comments.

Comments

4

If I understand correctly, you want to return single element right away. I do this by:

//When there is multiple entries expected but I only need the first
var wordForms = await db.WordForms
               .FirstOrDefaultAsync(w => w.Text == word);

or

//When I am sure only one entry exist
var wordForms = await db.WordForms
           .SingleOrDefaultAsync(w => w.Text == word);

If you do not need to await you can just use the default extension methods without await.

For Async SingleOrDefault and Async FirstOrDefault you must include Entity framework 6.

Why is there no SingleOrDefaultAsync for IQueryables?

https://msdn.microsoft.com/en-us/library/dn220208(v=vs.113).aspx

2 Comments

Will not work, you can only await a Task, not any other value
Edited to include Async approach
2

I would imagine that your terminal operation needs to be any of FirstAsync, FirstOrDefaultAsync, SingleAsync or SingleOrDefaultAsync.

I haven't checked, but I'm presuming that all of those variants exist.

1 Comment

Those would need implementation as a form of ToListAsync, already used
-3

So you just want the first value from WordForms that have Text==word?

var wordForms = (from c in db.WordForms
                where c.Text==word
                select c).FirstOrDefault()

1 Comment

Where's Async-Await

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.