I am writing a C# .NET 5 application that will act as a backend for an Angular frontend, providing CRUD APIs. The purpose of the app is managing a flight school.
I am writing the API methods that will return the list of pilots and the single pilot, that is https://myapp/api/pilots and https://myapp/api/pilots/{id}.
我这里有三种方法:
GetPilots()完整列表GetPilot(long idPilot)为了细节GetFlightTime(long idPilot),用于返回每个飞行员执行飞行持续时间总和的总飞行时间。我的问题:详细方法有效,因为我首先调用辅助函数,然后在返回的视图模型中使用结果。但GetPilots()不起作用并返回错误System.InvalidOperationException: The client projection contains a reference to a constant expression of 'QTBWeb.Models.PilotsRepository' through the instance method 'GetFlightTime'. This could potentially cause a memory leak; consider making the method static so that it does not capture constant in the instance.
这是因为我正在调用GetFlightTimeLINQ 表达式内的方法吗?我不明白使方法静态的建议。如何重新格式化代码以使其正常工作?
谢谢!
   public IEnumerable<PilotViewModel> GetPilots()  // THIS METHOD RETURNS ERROR
    {
        return _context.Pilots
            .Select(pilot => new PilotViewModel
            {
                Id = pilot.Id,
                Name = pilot.Name,
                FlightMinutes = GetFlightTime(pilot.Id)  // THE PROBLEM IS HERE
            })
            .ToList();
    }
    public PilotViewModel GetPilot(long idPilot)  // THIS METHOD WORKS
    {
        var _flightMinutes = GetFlightTime(idPilot);
        return _context.Pilots
            .Select(pilot => new PilotViewModel
            {
                Id = pilot.Id,
                Name = pilot.Name,
                FlightMinutes = _flightMinutes
            })
            .Where(pilot => pilot.Id == idPilot)
            .FirstOrDefault();
    }
    public int GetFlightTime(long idPilot)
    {
        return _context.Flights
            .Where(flight => flight.pilot == idPilot)
            .Select(flight => flight.Duration).Sum();  
    }
解决这个问题的一个好方法是确保您的Pilot类有一个 的集合Flights,作为您拥有的一对多映射的另一侧Flight.Pilot。然后,您可以使用此集合来计算总和,而无需在数据库中查询 的每个循环实例Pilot。
你的代码看起来像这样:
public IEnumerable<PilotViewModel> GetPilots()
    {
        return _context.Pilots
            .Include(pilot => pilot.Flights) // Include Flights to join data
            .Select(pilot => new PilotViewModel
            {
                Id = pilot.Id,
                Name = pilot.Name,
                FlightMinutes = pilot.Flights.Sum(flight => flight.Duration)
            });
    }
    public PilotViewModel GetPilot(long idPilot)
    {
        return _context.Pilots
            .Include(pilot => pilot.Flights) // Include Flights to join data
            .Where(pilot => pilot.Id == idPilot) // Notice how we filter first
            .Select(pilot => new PilotViewModel
            {
                Id = pilot.Id,
                Name = pilot.Name,
                FlightMinutes = pilot.Flights.Sum(flight => flight.Duration)
            })
            .FirstOrDefault();
    }
| 归档时间: | 
 | 
| 查看次数: | 18672 次 | 
| 最近记录: |