Reputation: 13
Need to check If body data Null and if Null filed, no need to check the particular WHERE clause.
How can I add multiple WHERE and OR clauses with NULL checking?
In CountryDialCodeFields
, some fields can be null sometimes.
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));
}
Upvotes: 0
Views: 1024
Reputation: 27282
Straightforward way:
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)
);
Or using extension:
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);
Upvotes: 0