4
votes

I have this interface :

public interface ISign
{
   Task<bool> IsRegisteredCopy();
}

Implemented it:

public class Sign : ISign
    {
        TabibContext context = new TabibContext();
        public Task<bool> IsRegisteredCopy()
        {
            return context.Doctors.Any();
        }
    }

So I need to return Task from Any method which is not available!

2
return context.Doctors.AnyAsync(); - DavidG
not available in the IntelliSense! - mshwf
Do you have the System.Data.Entity namespace imported? - DavidG
Nope, thought it exist in System.Data - mshwf

2 Answers

8
votes

Entity Framework has various async extensions you can use in the System.Data.Entity namespace. So you can do this:

using System.Data.Entity;

public Task<bool> IsRegisteredCopy()
{
    return context.Doctors.AnyAsync();
}
1
votes

You have several ways to do this. One of them is the Matthew Watson's way (return Task.Run(() => context.Doctors.Any());). It is not considered as a good practice (take a look at Stephen Cleary answers and links in this question).

Here is another way that does not requires you to actually run a Task. You can return a Task without having a task like this:

return Task.FromResult(context.Doctors.Any());

This way, you can return a value without triggering all the task stuff. It is a better practice when you don't actually have a task in your methods.

Note: on the last version of Entity Framework, you have a AnyAsync methods which is even better:

public async Task<bool> IsRegisteredCopy()
{
    return await context.Doctors.AnyAsync();
}

You will need to add this using: System.Data.Entity;