whoami
whoami

Reputation: 1899

convert method to wait until query finishes

I am loading some data from database using query below. Can I use this method to await until this query finishes using await-async?

public static void LoadData()
        {
            using (MyEntities entities = new MyEntities())
            {
                List<Employee> Employees = (from d in entities.Employees
                                            where d.Id > 100
                                            select new Employee
                                            {
                                                Name = d.LastName + ", " + d.FirstName
                                                DoB = d.dob
                                            }).ToList();
            }
}

Upvotes: 0

Views: 1490

Answers (2)

Marv
Marv

Reputation: 441

Yes, you can use this method http://msdn.microsoft.com/en-us/library/dn220262(v=vs.113).aspx;

public static async void LoadData()
    {
        using (MyEntities entities = new MyEntities())
        {
            List<Employee> Employees = await (from d in entities.Employees
                                        where d.Id > 100
                                        select new Employee
                                        {
                                            Name = d.LastName + ", " + d.FirstName
                                            DoB = d.dob
                                        }).AsQueryable().ToListAsync();
        }
}

If MyEntities is DbContext you can use

List<Employee> Employees = 
                   await entities.Set<Employee>()
                       .Where(d => d.Id > 100)
                       .Select(
                        d =>
                        new Employee
                        {
                            Name = d.LastName + ", " + d.FirstName,
                            DoB = d.dob
                        }).ToListAsync();

Upvotes: 0

Servy
Servy

Reputation: 203834

Entity Framework has a ToListAsync method as of EF 6.0 that returns a Task<List<T>>, allowing you to await it.

Upvotes: 5

Related Questions