Quindi, ho un problema con l'interrogazione di dati specifici dal mio database. Diciamo che ho due contesti contenenti oggetti di tipo:
TrackPoint {
int Id;
double Latitude;
double Longitude;
int TrackId
{
Track {
int Id;
double MinLatitude;
double MaxLatitude;
double MinLongitude;
double MaxLongitude;
}
Ogni traccia ha una quantità di TrackPoints assegnati. Voglio interrogare tutti i trackpoint, le cui tracce si intersecano con le altre tracce (le aree costruite dai valori min, max si sovrappongono).
Sto cercando di ottenere questo risultato con una sola query, poiché le prestazioni sono importanti. Sono riuscito a farlo con la query qui sotto, ma il tempo di esecuzione non è così buono. Sono sicuro che ci sono modi migliori per questo. Gradirei qualche consiglio.
var similarTrackPoints = Context.TrackPoints.Include("Track").Where(
tp =>
Context.Tracks.Where(t => t.Id == tp.TrackId).FirstOrDefault().MinLongitude <= track.MaxLongitude &&
Context.Tracks.Where(t => t.Id == tp.TrackId).FirstOrDefault().MaxLongitude >= track.MinLongitude &&
Context.Tracks.Where(t => t.Id == tp.TrackId).FirstOrDefault().MinLatitude <= track.MaxLatitude &&
Context.Tracks.Where(t => t.Id == tp.TrackId).FirstOrDefault().MaxLatitude >= track.MinLatitude)
.ToList();
Dovresti modellare le tue relazioni nelle tue entità. Quindi è possibile costruire più facilmente una query lambda o linq che risulta in una query corretta eseguita lato server DB.
public class TrackPoint
{
public int Id { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public double TrackId { get; set; }
public Track Track { get; set; }
}
public class Track
{
public double Id { get; set; }
public double MinLatitude { get; set; }
public double MaxLatitude { get; set; }
public double MinLongitude { get; set; }
public double MaxLongitude { get; set; }
public ICollection<TrackPoint> TrackPoints { get; set; }
}
Context.TrackPoints.Include("Track")
.Where(_ =>
_.Track.MinLongitude <= track.MaxLongitude &&
_.Track.MaxLongitude >= track.MinLongitude &&
_.Track.MinLatitude <= track.MaxLatitude &&
_.Track.MaxLatitude >= track.MinLatitude)
.ToList();
Non ho incluso i mapping delle relazioni nel codice sopra, ma puoi mappare la relazione usando le notazioni fluenti o degli attributi simili ad altre mappature EF.