【问题标题】:EF 6. Complex Query. Search and FilterEF 6. 复杂查询。搜索和过滤
【发布时间】:2015-09-27 16:57:50
【问题描述】:

我在我的 asp.net mvc 应用程序中使用 Entity Framework 6。 我对数据库有复杂的查询,导致大约 15 个表。 查询包括搜索和过滤。此查询执行速度很慢(在本地机器上大约需要 800 毫秒)。

query.Include(i => i.Customer) 
     .Include(i => i.Address) 
      ... 
     .Include(i => i.Photos)
     .Select(x => new {
      ...
      x.Address.City,
      CustomerName = i.Customer != null ? i.Customer.Name : "",
      ...
    });

...
//searching & filtering
// searchFilter.PropertyName and searchFilter.PropertyValue - strings!
// for example searchFilter.PropertyName = 'CustomerName'
 query = query.Where(String.Format("{0} == {1}", searchFilter.PropertyName, searchFilter.PropertyValue));
// PageIndex = 20
 query = query.Skip(PageIndex * PageSize).Take(PageSize)
...
 var result = query.ToList();
...

问题:

  1. 急切加载无法正常工作 - MiniProfiler 显示地址表的重复请求
  2. 这种搜索(使用“包含”)非常有限,因为我必须创建具有诸如客户之类的属性的匿名类型对象,以检查客户是否不为空(或更复杂的操作)并且必须在某处硬编码 PropertyName 的字符串(例如在调用 ajax 请求的 javascript 文件中)。

还有其他方法吗?

【问题讨论】:

    标签: c# performance entity-framework search linq-to-sql


    【解决方案1】:

    一些备注:

    • 您无需include(i => i.Address) 即可选择x.Address.City,也无需在where 子句中测试任何Address 属性
    • 只要你有一个 IQueryable 绑定到一个 Sql Server,CustomerName = i.Customer != null ? i.Customer.Name : "" 可以替换为CustomerName = i.Customer.Name ?? ""

    不确定这是否会对性能产生重大影响,但...

    否则,创建索引通常是提高性能的途径。

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多