首页 > 解决方案 > 从 EF 结果集中过滤现有条目

问题描述

我有一张现有客户及其客户 ID 的表格。当我向表中添加新客户时,我使用自动完成功能,但我想从结果集中排除现有客户。

这就是我到目前为止所拥有的:

public JsonResult AutoCompleteCustomerNumberLimit([FromBody] object value)
        {
            var input = new
            {
                value = ""
            };

            var existingEntries = luxWebSamContext.Limits.Select(u => u.PkKdnr).ToList();
            var company = JsonConvert.DeserializeAnonymousType(value.ToString(), input);

            var isNumeric = int.TryParse(company.value, out _);

            var result = (from c in AlContext.AutolineAccts
                          where EF.Functions.Like(
                               isNumeric ? c.AccountCode : c.CustomerSname, "%" + company.value + "%")
                                && !existingEntries.Contains(c.AccountCode)
                          select new
                          {
                              CompanyName = c.CustomerSname.Trim(),
                              CompanyNumber = c.AccountCode.Trim(),
                              CompanyStreet = c.AddressLine1.Trim(),
                              CompanyZip = c.Postcode.Trim(),
                              CompanyCity = c.AddressLine4.Trim(),
                              CompanyCountry = c.Eccode.Trim()

                          }).Distinct()
                            .Take(10);

            return Json(result);
        }

很容易跟上。existingEntries包含我想要从结果集中排除的现有客户的 ID 列表。company保存我的自动完成输入字段中的部分 ID 或名称。

问题是:这种代码正在我的应用程序的另一个功能中使用少量现有实体。但是在这里我在 30 秒后超时。等待查询结束。我在现有条目列表中有 11.000 行,这对于这种查询来说可能太多了。

这里有什么想法吗?

我试图将工作量分成两个步骤:

首先,我检索包括现有客户在内的结果:

var result = (from c in AlContext.AutolineAccts
                              where EF.Functions.Like(
                                   isNumeric ? c.AccountCode : c.CustomerSname, "%" + company.value + "%")
                                    
                              select new
                              {
                                  CompanyName = c.CustomerSname.Trim(),
                                  CompanyNumber = c.AccountCode.Trim(),
                                  CompanyStreet = c.AddressLine1.Trim(),
                                  CompanyZip = c.Postcode.Trim(),
                                  CompanyCity = c.AddressLine4.Trim(),
                                  CompanyCountry = c.Eccode.Trim()
    
                              }).Distinct()
                                .Take(10);

然后我从结果中删除现有客户......类似的东西,但我的语法不正确:

   result = result.Where(x => x.CompanyNumber != existingEntries.);

标签: entity-frameworkasp.net-core.net-coreentity-framework-core

解决方案


推荐阅读