1

我将 LINQ 与 EntityFramewwork 6 一起使用,并且我需要将大部分方法转换为异步任务。

但是,我无法弄清楚为什么在这两个特定场景中我会收到这些设计时编译消息。如果有人可以向我解释我需要做什么才能使任务异步,将不胜感激。

我要转换的第一类同步任务如下:

public List<Category> GetProjectsByCategoryID(Int16 categoryid)
        {
            try
            {
                using (YeagerTechEntities DbContext = new YeagerTechEntities())
                {
                    DbContext.Configuration.ProxyCreationEnabled = false;
                    DbContext.Database.Connection.Open();

                    var category = DbContext.Categories.Include("Projects").Where(p => p.CategoryID == categoryid).ToList();

                    return category;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

当我尝试将上述方法更改为异步任务时(见下文),我不知道该放置什么异步方法inbetween the "Include("Projects").(p"

public async Task<List<Category>> GetProjectsByCategoryID(Int16 categoryid)
        {
            try
            {
                using (YeagerTechEntities DbContext = new YeagerTechEntities())
                {
                    DbContext.Configuration.ProxyCreationEnabled = false;
                    DbContext.Database.Connection.Open();

                    var category = await DbContext.Categories.Include("Projects").(p => p.CategoryID == categoryid);

                    return category;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

如何将此同步方法转换为异步方法?

public List<CustomerEmail> GetCustomerDropDownList()
        {
            try
            {
                using (YeagerTechEntities DbContext = new YeagerTechEntities())
                {
                    DbContext.Configuration.ProxyCreationEnabled = false;
                    DbContext.Database.Connection.Open();

                    var customers = DbContext.Customers.Select(s =>
                        new CustomerEmail()
                        {
                            CustomerID = s.CustomerID,
                            Email = s.Email
                        }).ToList();

                    return customers;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
4

1 回答 1

2

你非常非常接近:

public async Task<List<CustomerEmail>> GetCustomerDropDownList()
{
    try
    {
        using (YeagerTechEntities DbContext = new YeagerTechEntities())
        {
            DbContext.Configuration.ProxyCreationEnabled = false;
            DbContext.Database.Connection.Open();

            var customers = await DbContext.Customers.Select(s =>
            new CustomerEmail()
            {
                CustomerID = s.CustomerID,
                Email = s.Email
            }).ToListAsync();

            return customers;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

注意 ToListAsync()。这将显式加载和解析您的查询,但将以异步方式执行此操作。

于 2013-11-04T22:47:08.797 回答