我需要获取记录列表并根据条件过滤它们:如果serviceId = 1,那么我需要将该结果与serviceId = 5的结果结合起来。
型号:
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; }
}
我的代码只有一个过滤器:
var serviceId = 1;
var partners = dbContext.Partners.Where(p => p.PartnerServiceBrands.Select(psb => psb.Service.Id).Contains(serviceId));
我试着这样做:
if (serviceId == 1)
{
var partners2 = dbContext.Partners.Where(p => p.PartnerServiceBrands.Select(psb => psb.Service.Id).Contains(5));
partners = partners.Union(partners2); // Error
}
我还尝试将Contains
与List<int>
一起使用,但我无法启动并运行。
修改
我得到的错误是:
异常:抛出:&#34;地理数据类型不能被选为DISTINCT,因为它不具有可比性。&#34; (System.Data.SqlClient.SqlException)
答案 0 :(得分:1)
我对此的看法。
根据您要过滤的serviceIds
列表:
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 :(得分:1)
您收到错误是因为Union()
使用UNION ALL
生成SELECT DISTINCT
。旁边Concat()
仅产生UNION ALL
。
无论如何,我认为你应该能够通过以下方式得到你想要的东西:
var serviceIds = new List<int>{ 1, 5 };
var partners = dbContext.Partners
.Where(p => p.PartnerServiceBrands.Any(psb => serviceIds.Contains(psb.Service.Id))
答案 2 :(得分:0)
也许这会奏效:
var partners = dbContext.Services
.Where(ser => ser.Id == 1 || s.Id == 5).SelectMany(ser => ser.PartnerServiceBrands)
.Select(psb => psb.Partner).Distinct();
答案 3 :(得分:0)
假设您DbSet<Service>
为Services
,我会尝试:
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();