0

需要检查 If body data Null 和如果 Null 归档,不需要检查特定的 WHERE 子句。如何使用 NULL 检查添加多个 WHERE 和 OR 子句?在CountryDialCodeFields中,某些字段有时可能为空。

 public class CountryDialCodeFields
    {
        public string countryCode { get; set; }
        public string countryName { get; set; }
        public string dialCode { get; set; }
        public string currencyCode { get; set; }
    }


[HttpGet("/api/country-details")]
public IActionResult CountryDetailGet(CountryDialCodeFields BodyData)
{
var CountryDataSet22 = CountryCodeDbContext.Countrydetails.Where( x => (BodyData.countryCode != null ? x.Countrycode == BodyData.countryCode) &&
             (BodyData.countryName != null ? x.Countryname == BodyData.countryName) &&
             (BodyData.currencyCode != null ? x.Currencycode == BodyData.currencyCode) &&
             (BodyData.currencyCode != null ? x.Dialcode == BodyData.dialCode));
}
4

1 回答 1

0

直截了当的方法:

var CountryDataSet22 = CountryCodeDbContext.Countrydetails
    .Where(x => 
            (BodyData.countryCode  == null || x.Countrycode  == BodyData.countryCode)  &&
            (BodyData.countryName  == null || x.Countryname  == BodyData.countryName)  &&
            (BodyData.currencyCode == null || x.Currencycode == BodyData.currencyCode) &&
            (BodyData.dialCode     == null || x.Dialcode     == BodyData.dialCode)
    );

或使用扩展:

public static class MyQueryableExtensions
{
    public static IQueryble<T> WhereIf<T>(this IQueryable<T> source, bool condiion, Expression<Func<T, bool> predicate)
    {
        if (condition)
            source = source.Where(predicate);
        return source;
    }
}
var CountryDataSet22 = CountryCodeDbContext.Countrydetails
    .WhereIf(BodyData.countryCode  != null, x => x.Countrycode  == BodyData.countryCode)
    .WhereIf(BodyData.countryName  != null, x => x.Countryname  == BodyData.countryName)
    .WhereIf(BodyData.currencyCode != null, x => x.currencyCode == BodyData.currencyCode)
    .WhereIf(BodyData.dialCode     != null, x => x.Dialcode     == BodyData.dialCode);
于 2022-03-03T11:17:38.337 回答