不同列的搜索方法

时间:2019-07-15 12:54:05

标签: c# linq properties entity-framework-core

我有FormComboBoxTextBox。第一个包含列名,第二个包含要搜索的文本。 ComboBoxListTypeSearch元素中提取ItemSearch作为源。在按下Search()按钮的过程中调用Search方法。

如果给列起这样的名字,将找不到任何内容

EF.Functions.Like(item.Value, ...); // Value = "FullName"

如果从模型中指定一列,则搜索有效

EF.Functions.Like(w.FullName, ...); 

是否可以替换应该在同一Search()方法中搜索的列?

ListTypeSearch.Add(new ItemSearch { Value = "FullName", Display = "some text" });
ListTypeSearch.Add(new ItemSearch { Value = "PassportSeries", Display = "some text" });
ListTypeSearch.Add(new ItemSearch { Value = "PassportNumber", Display = "some text" });

public class ItemSearch
{
    public string Value { get; set; }
    public string Display { get; set; }
}

internal List<WorkerTableRow> Search(ItemSearch item, string text)
{
    try
    {
        Found = new List<WorkerTableRow>();
        using (ModelContext model = new ModelContext())
        {
            Found = (from w in model.Workers
                     where EF.Functions.Like(w.FullName, // this code
                                             String.Format("%{0}%", text))
                     select new WorkerTableRow
                     {
                         ...
                     })
                     .ToList();
        }
    }
    catch (Exception ex) { ... }

    return Found;
}

更新

现在我确实喜欢这样。其作品。可以简化吗?

where EF.Functions.Like(w.GetProperty(item.Value), 
                        String.Format("%{0}%", text))


public partial class Workers
{
    ...

    public string FullName { get; set; }
    public string PassportSeries { get; set; }
    public string PassportNumber { get; set; }

    public string GetProperty(string name)
    {
        switch (name)
        {
            case "FullName":
                return FullName;
            case "PassportSeries":
                return PassportSeries;
            case "PassportNumber":
                return PassportNumber;
            default:
                return string.Empty;

        }
    }
}

1 个答案:

答案 0 :(得分:0)

根据其他answer。如果使用Like(w.GetProperty(item.Value), ...),则请求在客户端而不是服务器上执行。要将整个请求发送到服务器,您可以执行以下操作:

List<WorkerTableRow> Search(ItemSearch item, string text)
{
    string pattern = string.Format("%{0}%", text);

    using (var model = new ModelContext())
    {
        IQueryable<Worker> query = model.Workers;

        if (item.Value == "FullName")
            query = query.Where(w => EF.Functions.Like(w.FullName, pattern));

        if (item.Value == "PassportSeries")
            query = query.Where(w => EF.Functions.Like(w.PassportSeries, pattern));

        if (item.Value == "PassportNumber")
            query = query.Where(w => EF.Functions.Like(w.PassportNumber, pattern));

        return query.Select(w => new WorkerTableRow { ... }).ToList();
    }
}