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)

+3


source to share


4 answers


I accept this.

Given the list serviceIds

you want to filter:



var serviceIds = new List<int>{1, 5};

var partners = dbContext.Services
    .Where(ser => serviceIds.Contains(ser.Id).SelectMany(ser => ser.PartnerServiceBrands)
    .Select(psb => psb.Partner).Distinct();

      

+1


source


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))

      

+1


source


Maybe this will work:

var partners = dbContext.Services
    .Where(ser => ser.Id == 1 || s.Id == 5).SelectMany(ser => ser.PartnerServiceBrands)
    .Select(psb => psb.Partner).Distinct();

      

0


source


Assuming you have DbSet<Service>

both Services

, I would try:

var serviceId = ...;

var partners = dbContext.Services
      .Where(svc => svc.Id == serviceId || (serviceId == 1 && svc.Id == 5))
      .SelectMany(svc => svc.PartnerServiceBrands)
      .Select(psb => psb.Partner).Distinct();

      

0


source







All Articles