实体框架ToListAsync()与Select() [英] Entity Framework ToListAsync() with Select()

查看:127
本文介绍了实体框架ToListAsync()与Select()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有以下ActionResult

I have the following ActionResult in my controller

public async Task<ActionResult> NewTickets()
{
    // Show tickets for all divisions a agent is in

    var user = "abcdefg";
    var company = "company1";

    var tickets = (from a in db2.Ticket
        join c in db2.Division on a.DivisionId equals c.DivisionId
        join dp in db2.DivisionParticipator on c.DivisionId equals dp.DivisionId
        where c.CompanyId == company.CompanyId && a.Status == "New" && dp.ApplicationUserId == user.Id
        select new
        {
            Id = a.Id,
            DivisionId = a.DivisionId,
            Name = a.Name,
            TicketDate = a.TicketDate,
            NewPosts = a.NewPosts,
            Status = a.Status,
            Type = a.Type
         })
         .ToList().Select(x => new Ticket
         {
             Id = x.Id,
             DivisionId = x.DivisionId,
             Name = x.Name,
             TicketDate = x.TicketDate,
             NewPosts = x.NewPosts,
             Status = x.Status,
             Type = x.Type
          });            

    return PartialView(tickets.ToList());
}

我要实现的是运行此异步,但是,如果在 Select() Select()方法之前添加 ToListAsync()变得不可用.对于 return PartialView(tickets.ToList())也是如此.

What i want to achieve is running this async, however if adding the ToListAsync()before Select()the Select() method becomes unavailable. The same goes for the return PartialView(tickets.ToList()).

我对使用异步技术还很陌生,但是在阅读它的优点时,我一直在将常规ActionResult方法与异步方法进行融合.到目前为止,使用基于LINQ的查询更轻松,这种情况一直很好.但是,对于此ActionResult方法,查询要稍微先进一些,并且实现它的语法/方式似乎有所不同.

I'm fairly new to working with async but reading about it's advantages I have been convering regular ActionResult methods with async ones. This has been going fine so far with easier LINQ-based queries. However for this ActionResult-method the query is a bit more advanced and the syntax/way to implement it seems to differ.

任何对向正确方向发送我的帮助将不胜感激!

Any help to send me in the right direction would be greatly appreciated!

推荐答案

分为两个语句:

var tickets0 = await (from ...).ToListAsync();

var tickets = tickets0.Select(...);

.ToListAsync()返回 Task ,因此它不接受 .Select 扩展方法,该方法需要一些 IEnumerable .仅当您等待该任务时,您才会获得 List .

The .ToListAsync() returns a Task, so it doesn't accept the .Select extension method, which will need some IEnumerable. Only when you await that Task, you will get the List.

另一种方式(不太可读的IMO)将是:

Another way (less readable IMO) would be:

 var tickets = (await (from ...).ToListAsync()).Select(...);

请注意await子句周围的多余(),这意味着Select将对等待的代码的结果起作用,而不是对Task起作用.

Note the extra ( ) around the await clause, which mean that the Select will work on the result of the awaited code, instead of the Task.

这篇关于实体框架ToListAsync()与Select()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆