簡體   English   中英

C# LINQ 在搜索過程中忽略空值的實體框架查詢

[英]C# LINQ Entity Framework query that ignores nulls as part of the search

我有一個 model 我試圖從中創建 LINQ 查詢。 model 包含多個屬性,其中一些可以是 null。

我想創建一個不嘗試搜索 null 或空值屬性的 LINQ 語句。

例子:

public class MySearch
{
   public string Prop1 { get; set; }
   public decimal? Prop2 { get; set; }
   public int? Prop3 { get; set; }
}

我想要一個 LINQ 語句,當它是 null 時忽略一個屬性。

就像是:

var searchResults = myContext.MyStuff
            .Where(

   //If Prop1 is not null, but Prop2 and Prop3 ARE null, only query on Prop1
   //If Prop1 and Prop2 are not null, but Prop3 is null, query on Prop1 and Prop2
   //If Prop2 and Prop3 are not null, but Prop1 is null, query on Prop2 and Prop3
   //etc.

            );

正如其他人指出的那樣,只需像這樣更改您的代碼:

var searchResults = myContext.MyStuff;

if (Prop1 != null)
{
    searchResults = searchResults.Where(def => def.prop == mySearch.Prop1);
}     

if (Prop2 != null)
{
    searchResults = searchResults.Where(def => def.prop == mySearch.Prop2);
}     

if (Prop3 != null)
{
    searchResults = searchResults.Where(def => def.prop == mySearch.Prop3);
}     

// At this point the query has not executed yet.

return searchResults.ToArray(); // here, the query has run.

暫無
暫無

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

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