如何 return FirstOrDefaultAsync EF Linq 到实体列表查询

How to return FirstOrDefaultAsync EF Linq to entity List query

我有这个 Linq 到实体查询,return 是一个具有连接的访问​​者列表。
我想要一个类似于 return 单个记录的查询,但查询不是列表集合,但是将其更改为带有 FirstOrDefaultAsync 的基本 select 会得到错误 "A query body must end with a select clause or a group clause"

public async Task<List<VisitorDetail>> GetOneVisitor(int visitorId)
{
    var query = await (from v in _context.Visitors
        where v.Id == visitorId
        join d in _context.Categories on v.VisitCategoryId equals d.Id
        join c in _context.Counters on v.AssignedCounter equals c.Host into counterGroup
        from cg in counterGroup.DefaultIfEmpty()
        select new
        {
            FirstName = v.FirstName,
            LastName = v.LastName,
            CounterDescription = cg.Description,
            VisitCategory = d.Description
        }).ToListAsync();

    List<VisitorDetail> visitors = new();

    foreach (var p in query)
    {
        visitors.Add(new VisitorDetail
        {
            FirstName = p.FirstName,
            LastName = p.LastName,
            CounterDescription = p.CounterDescription,
            CategoryDescription = p.VisitCategory
        });
    }
    return visitors;
}

如果您想使用 LINQ to Entities 保持 DRY,return IQueryable 用于您的常见查询并仅在需要时调用具体化。

您的方法可以按以下方式重写:

public IQueryable<VisitorDetail> GetVisitorDetails(int visitorId)
{
    var query = 
        from v in _context.Visitors
        where v.Id == visitorId
        join d in _context.Categories on v.VisitCategoryId equals d.Id
        join c in _context.Counters on v.AssignedCounter equals c.Host into counterGroup
        from cg in counterGroup.DefaultIfEmpty()
        select new VisitorDetail
        {
            FirstName = v.FirstName,
            LastName = v.LastName,
            CounterDescription = cg.Description,
            CategoryDescription = d.Description
        };

    return query;
}
var many = await GetVisitorDetails(visitorId).ToListAsync();
var one  = await GetVisitorDetails(visitorId).FirstOrDefaultAsync();