Conditional filter using LINQ with C #
I need to get a list of records and filter them based on the condition: if serviceId = 1, then I need to match this result with the result for serviceId = 5.
Models:
public class Partner
{
[Key]
public int Id { get; set; }
public DbGeography Location { get; set; }
public virtual ICollection<PartnerServiceBrand> PartnerServiceBrands { get; set; }
}
public class PartnerServiceBrand
{
[Key]
public int Id { get; set; }
public virtual Partner Partner { get; set; }
public virtual Service Service { get; set; }
}
public class Service
{
[Key]
public int Id { get; set; }
public virtual ICollection<PartnerServiceBrand> PartnerServiceBrands { get; set; }
}
My code for just one filter:
var serviceId = 1;
var partners = dbContext.Partners.Where(p => p.PartnerServiceBrands.Select(psb => psb.Service.Id).Contains(serviceId));
I tried to do:
if (serviceId == 1)
{
var partners2 = dbContext.Partners.Where(p => p.PartnerServiceBrands.Select(psb => psb.Service.Id).Contains(5));
partners = partners.Union(partners2); // Error
}
I also tried to use Contains
with List<int>
, but I was unable to get it up and running.
EDIT
The error I am getting:
Exception: Thrown: "Geography type cannot be selected as DISTINCT because it is not comparable." (System.Data.SqlClient.SqlException)
source to share
You get an error because it Union()
generates UNION ALL
with SELECT DISTINCT
. Since Concat()
only a is obtained aside UNION ALL
.
Anyway, I think you should be able to get what you are looking for, for example:
var serviceIds = new List<int>{ 1, 5 };
var partners = dbContext.Partners
.Where(p => p.PartnerServiceBrands.Any(psb => serviceIds.Contains(psb.Service.Id))
source to share