2015-02-24 111 views
-1

我想创建动态LINQ查询C#动态LINQ查询EF 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场,所以它不是可以写入每场

+1

这可能有助于http://weblogs.asp.net/scottgu/dynamic-linq-part-1-using-the-linq-dynamic-query-library – 2015-02-24 11:43:17

回答

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();

这意味着它将获取CandidateId Contains在answerList中的所有候选人。

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中可以做的那样。

希望这会帮助你。

+0

但是我可以写linq查询使用哪里超过一个领域动态.. – 2015-02-25 09:08:12

+0

不,你必须在案件的基础上写条件的地方。这是我曾发布有关此原始文章http://stackoverflow.com/questions/23557509/use-dynamic-linq-library-with-join – Sunny 2015-02-26 04:26:00

+0

有解决方案使用“System.Linq.Dynamic”感谢Sunny。 – 2015-02-27 11:52:36