更改linq查询以获得最佳性能

时间:2013-07-11 05:42:47

标签: c# linq

我正在进行性能改进任务以优化LINQ-SQL查询逻辑。   有人可以建议最佳的优化查询。这是我的查询

var localResponse = (from p in context.Places                                 
                     where (p.PlaceName.Contains(searchText))
                         && (p.MkTypeId == MkType.Premise)
                         && p.PlaceName != null
                         && p.ObjectState != ObjectState.Deleted
                     select new Prediction {
                                    value = p.PlaceName,
                                    id = p.APIPlaceId,
                                    reference = p.APIPlaceReference,
                                    latitude = p.Location.Latitude,
                                    longitude = p.Location.Longitude,
                                    addressId = p.AddressId,
                                    bedroom = p.Bedroom,
                                    placeTypeId = p.PlaceTypeId,
                                    placeId = p.Id
                             })
                     .Union(from p in context.Places
                            join cp in context.Places on p.Id equals cp.ParentPlaceId
                            where (p.PlaceName.Contains(searchText) || cp.PlaceName.Contains(searchText))
                                && (p.MkTypeId == MkType.Premise || p.MkTypeId == MkType.Room)
                                && p.PlaceName != null
                                && cp.PlaceName != null
                                && p.ObjectState != ObjectState.Deleted
                                && cp.ObjectState != ObjectState.Deleted
                            select new Prediction {
                                           value = cp.PlaceName + ", " + p.PlaceName,
                                           id = p.APIPlaceId,
                                           reference = p.APIPlaceReference,
                                           latitude = p.Location.Latitude,
                                           longitude = p.Location.Longitude,
                                           addressId = p.AddressId,
                                           bedroom = p.Bedroom,
                                           placeTypeId = p.PlaceTypeId,
                                           placeId = p.Id  });

这是预测类

 public class Prediction
{
    public string id { get; set; }
    public string reference { get; set; }
    public string value { get; set; }
    public double? latitude { get; set; }
    public double? longitude { get; set; }
    public int? addressId { get; set; }
    public int? bedroom { get; set; }
    public PlaceType placeTypeId { get; set; }
    public int? placeId { get; set; }
}

提前致谢

1 个答案:

答案 0 :(得分:1)

我会尝试通过在Places和ParentPlaces上执行左外连接来避免UNION语句。除此之外,查询的主要问题是表达式“Contains(SearchText)”。它强制所有剩余记录(未删除和PlaceName不为空)在顺序扫描中逐个迭代(扫描所有记录)。这需要全文搜索。因此,请尝试查看您的数据库是否支持此功能。