convert 方法等待查询完成
convert method to wait until query finishes
我正在使用下面的查询从数据库中加载一些数据。我可以使用此方法等待直到此查询使用 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();
}
}
Entity Framework 从 EF 6.0 开始有一个 ToListAsync
方法,即 returns 一个 Task<List<T>>
,允许您 await
它。
是的,你可以使用这个方法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();
我正在使用下面的查询从数据库中加载一些数据。我可以使用此方法等待直到此查询使用 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();
}
}
Entity Framework 从 EF 6.0 开始有一个 ToListAsync
方法,即 returns 一个 Task<List<T>>
,允许您 await
它。
是的,你可以使用这个方法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();