我正在使用下面的查询从数据库加载一些数据。我可以使用此方法等待此查询完成使用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();
}
}
答案 0 :(得分:5)
实体框架自EF 6.0起有一个ToListAsync
方法,返回Task<List<T>>
,允许您await
。
答案 1 :(得分:0)
是的,您可以使用此方法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();
}
}
如果MyEntities是DbContext,您可以使用
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();