Last post Jul 01, 2017 09:12 AM by PatriceSc
Jul 01, 2017 08:49 AM|bluMarmalade|LINK
This might be a bit of a newbie question but I think it's important.
fetching data from db like normal:
var item = await _context.Documents.SingleOrDefaultAsync(z => z.ID == id);
Is it good practice it wrap this in try catch blocks every time? like this:
var item = new Document()
item = await _context.Documents.SingleOrDefaultAsync(z => z.ID == id);
But if the item does not excist no exception is thrown. Checking if the item is null will not work. So how can I check if i've got the data I want so that I can do further operations on the item without getting exceptions?
Jul 01, 2017 09:12 AM|PatriceSc|LINK
Use SingleOrDefaultAsync if you expect 1 or 0 match (and then you explicitely test for null to act accordingly as part of your expected code flow).
Here it seems you expect exactlyt 1 match in which case you should use SingleAsync (which will throw if you don't have exactly one match).
Edit: to be on the safe side SingleOrDefault returns null if no match is found (rather than a newly intialized object).