簡體   English   中英

動態 Linq 查詢 EF c#

[英]Dynamic Linq Query EF c#

我想創建動態 linq 查詢 c#

我做了很多谷歌搜索,但沒有得到確切的解決方案

我有以下領域的候選人(列出了幾個)
候選人編號
職位編號
城市編號
部門編號

我想使用動態數據創建 linq 查詢,例如

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

我需要像CandidateCityId(或其他)包含在idArray中的動態查詢

我在候選表中有 50 多個字段,所以不可能為每個字段都寫

我在開發庫存搜索窗口時遇到了同樣的問題。 我也在網上搜索了很多,但沒有成功。 我已經解決了這個問題,如下所示。

以下是我的搜索窗口:

在此處輸入圖片說明

在這里您可以看到有 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 });

現在在列表中,我擁有所有有價值的搜索條件。 現在我必須從數據庫中過濾記錄。 為此,我首先從數據庫中選擇所有記錄,然后根據列表項使用 switch,例如:

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

希望這會幫助你。

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 的所有候選人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM