动态Linq查询EF c#

时间:2015-02-24 11:37:17

标签: c# linq entity-framework

我想创建动态linq查询c#

我谷歌搜索很多,但没有得到确切的解决方案

我有以下领域的候选人(列出少数)
CandidateId
JobTitleId
CityId
DepartmentID的

我想用动态数据创建linq查询,如

var idArray=[1,2,3,4]
var fieldName='CityId' (may be any other of candidate Table)

我需要动态查询,例如candidateCityId(或其他)包含在idArray

我在候选表中有超过50个字段,因此无法为每个字段编写

2 个答案:

答案 0 :(得分:0)

在开发库存搜索窗口时,我遇到了同样的问题。我也在网上搜索了很多但没有成功。我已经解决了这个问题,如下所示。

以下是我搜索的窗口:

enter image description here

在这里你可以看到有6个组合框,每个组合框有四个选项:

  <ComboBoxItem IsSelected="True">Contains</ComboBoxItem>
                                <ComboBoxItem>Does Not Contain</ComboBoxItem>
                                <ComboBoxItem>Begins With</ComboBoxItem>
                                <ComboBoxItem>Ends With</ComboBoxItem>

我通过将列表中的选择和值存储为:

解决了这个问题
public class FilterList
{
    public string combobox { get; set; }
    public string value { get; set; }
}

在搜索按钮上单击:

 List<FilterList> filter = new List<FilterList>();
            filter.Add(new FilterList { combobox = cmbPart.Text, value = txtPart.Text });
            filter.Add(new FilterList { combobox = cmbDescription.Text, value = txtDescription.Text });
            filter.Add(new FilterList { combobox = cmbVendor.Text, value = txtVendor.Text });
            filter.Add(new FilterList { combobox = cmbVendorPart.Text, value = txtVendorPart.Text });
            filter.Add(new FilterList { combobox = cmbManufacture.Text, value = txtManufacture.Text });
            filter.Add(new FilterList { combobox = cmbManuPartNumber.Text, value = txtManuPartNumber.Text });

现在列表中我有所有搜索条件的值。现在我必须从数据库中过滤记录。 首先我从数据库中选择所有记录,然后根据列表项使用开关:

        if (!string.IsNullOrEmpty(filter[0].value))
                {
                    switch (filter[0].combobox)
                    {
                        case "Contains":
                        break;
                        case "Does Not Contain":
                        break;
                 }}
                if (!string.IsNullOrEmpty(filter[1].value))
                {
                    switch (filter[1].combobox)
                    {
                        case "Contains":
                        //code
                 }}

如果您可以在列表中使用来自数据库的不同查询。

总的来说,你可以说在linq中创建运行时查询是不可能的,就像在sql中一样。

希望这会对你有所帮助。

答案 1 :(得分:0)

var answerList = new List(){1,2,3,4};//from DB 
var fieldName= FieldDBPath; //from db //eg. CandidateId
var queryableData = _dbEntities.Candidates.Where("@0.Contains(outerIt."+fieldName + ")", answerList).ToList();

这意味着它在answerList中使用CandidateId Contains获取所有候选者。