Reputation: 1
I have the following code inside my asp.net core mvc:-
var result = await _context.Settings.SingleOrDefaultAsync(a => a.Name.ToLower() == "noofvisits").Result.Value;
but i got this error:-
Error CS1061 'string' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
so why i am getting this error? Thanks
Upvotes: 0
Views: 567
Reputation: 36755
If you want to get the single object,using:
var result = await _context.Settings
.SingleOrDefaultAsync(a => a.Name.ToLower() == "noofvisits");
If you want to get the single property in the object,using:
var result = await _context.Settings.Where(a => a.Name.ToLower() == "noofvisits")
.Select(s => s.PropertyName).FirstOrDefaultAsync();
Upvotes: 1
Reputation: 3877
You are specifying an await
for an asynchronous call that you are subsequently blocking on the result for. By adding .Result
, your code is now acting synchronously, returning a string and not a Task that can be awaited, which is what the await
keyword is meant for.
The return type of SingleOrDefaultAsync()
is a Task<T>
where T
is whatever data type that is supposed to return. With the await
, you are telling your code "Hey, whenever that task finishes and gives me a result, I'm waiting for that result".
If the expected data type is already a string, you don't have to do anything, you'd get a string back by doing:
string result = await _context.Settings.SingleOrDefaultAsync(a => a.Name.ToLower() == "noofvisits");
If it's a more complex POCO or something you need to grab a string from synchronously after you get the result, then you can do so after the task has finished:
var result = await _context.Settings.SingleOrDefaultAsync(a => a.Name.ToLower() == "noofvisits");
string yourString = result.DoWhateverHere();
Upvotes: 2