Entity Framework Linq Query: How to Where on Multiple Nav Properties and Select from 3rd Nav Property

限于喜欢 提交于 2019-12-11 17:33:43

问题


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:


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"



来源:https://stackoverflow.com/questions/47870578/entity-framework-linq-query-how-to-where-on-multiple-nav-properties-and-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!