简体   繁体   English

使用EF在Linq中搜索查询

[英]Search Query in Linq with EF

Lets say I have the following classes for Entity Framework 5 Code First. 可以说我有以下用于Entity Framework 5 Code First的类。 I need to do a search of all the Industries or Divisions for an array of keywords, returning all the Leads that match any of the keywords. 我需要在所有行业或部门中搜索一组关键字,并返回与任何关键字匹配的所有潜在客户。 I also need to search the Name of the Lead for the same keywords. 我还需要搜索潜在客户的名称以查找相同的关键字。 What I'm stuck on is how to search for multiple keywords. 我所坚持的是如何搜索多个关键字。

Main Class 主班

public class Lead
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Industry> Industries { get; set; }
    public virtual ICollection<Division> Divisions { get; set; }
}

Industry Class 行业类别

public class Industry
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Lead> Leads { get; set; }
}

Division Class 师级

public class Division
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Lead> Leads { get; set; }
}

Service / Repository Call 服务/存储库调用

public IQueryable<Lead> GetByKeywords(string keyword)
    {
        var result = leadRepository.GetAll().Where
            (x => x.Industries.Any(i => i.Name == keyword)
            || x.Divisions.Any(d => d.Name == keyword)
            || x.Name.Contains(keyword));

        return result;
    }

The above query works for a single keyword. 以上查询适用于单个关键字。 But it does not work if I have multiple words in the string and I want to match to any of the individual keywords. 但是,如果我在字符串中有多个单词,并且想要与任何单个关键字匹配,那将不起作用。

public IEnumerable<Lead> GetByKeywords(string[] keywords)
    {
        var result = GetAll().Where
            (x =>x.Industries.Any(i => keywords.Any(kw=>kw==i.Name))
            || x.Divisions.Any(d =>keywords.Any(k=>x.Name==k))
            || keywords.Any(kew => x.Name.Contains(kew)));

        return result;
    }

You'll need to split your string into a List and loop through each keyword. 您需要将字符串拆分成一个列表,然后遍历每个关键字。 Something like this... (off the top of my head) 像这样...(我的头顶)

IQueryable<Lead> GetByKeywords(string allKeywords)
{
    List<string> keywords = allKeywords.Split(" ");
    var result = leadRepository.GetAll();

    foreach (string keyword in keywords)
    {
        result = result.Where
            (x => x.Industries.Any(i => i.Name == keyword)
            || x.Divisions.Any(d => d.Name == keyword)
            || x.Name.Contains(keyword));
    }

    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM