Entity Framework Linq Query: How to Where on Multi

2019-08-25 08:45发布

I have the following models with nav propertiers set up in Entity Framework Core:

  • CRMLocations (one-to-many) CRMPeoples
  • CRMPeoples (one-to-many) CRMEmails
  • CRMPeoples (one-to-many) CRMPhones

I have the following working Query:

        var iqable = _crmDbContext.CRMPeoples
            .Where(p =>
                p.Name.ToLower().Contains(query) ||
                (from e in p.CRMEmails where e.EmailAddress.ToLower().Contains(query) select e).Any() ||
                (from h in p.CRMPhones where h.PhoneNumberNormalized.Contains(query) select h).Any())
            .Select(p => new CRMSearchResultDTO()
            {
                PersonName = p.Name,
                LocationName = p.CRMLocations.Name,
            });

How can I replace the "(from in where select).Any()" statements to use Linq's lambda syntax? Must result in 1 SQL statement. Can use left outter joins, or nested select.

1条回答
做个烂人
2楼-- · 2019-08-25 08:59
var iqable = _crmDbContext.CRMPeoples
        .Where(p =>
            p.Name.ToLower().Contains(query) ||
            p.CRMEmails.Where(e => e.EmailAddress.ToLower().Contains(query)).Any() ||
            p.CRMPhones.Where(h => h.PhoneNumberNormalized.Contains(query)).Any())
        .Select(p => new CRMSearchResultDTO()
        {
            PersonName = p.Name,
            LocationName = p.CRMLocations.Name,
        });

I got this code by using ReSharper's command "Convert LINQ to method chain"

查看更多
登录 后发表回答