如何在LINQFROM语句中执行OR

如何在LINQFROM语句中执行OR,linq,Linq,我正在尝试编写一个LINQ查询,其中我希望根据前端返回的内容访问两个不同表中的数据 如果从前端发送FlowerClients,我想使用FlowerClient表,或者如果发送的数据是用于另一个客户机 这是可以在LINQ中实现的,还是创建不同的方法更好 var flowerById = (from flower in flowerContext.Flowers where flower.FlowerId == flowerId join petals in flow

我正在尝试编写一个LINQ查询,其中我希望根据前端返回的内容访问两个不同表中的数据 如果从前端发送
FlowerClients
,我想使用
FlowerClient
表,或者如果发送的数据是用于另一个客户机

这是可以在LINQ中实现的,还是创建不同的方法更好

var flowerById = (from flower in flowerContext.Flowers
        where flower.FlowerId == flowerId
        join petals in flowerContext.Petals on flower.PetalId equals petals.PetalId
        from flowerClients in flowerContext.FlowerClients.Where(x => x.FlowerId == flower.FlowerId).DefaultIfEmpty()
        ||
        from anotherFlowerClients in flowerContext.AnotherClients.Where(x => x.FlowerId == flower.FlowerId).DefaultIfEmpty()

您可能需要创建不同的方法,尤其是当
FlowerClients
其他客户机
类非常不同时

否则,可以动态生成查询表达式。您可能希望确保
FlowerClients
AnotherClients
实现一个公共接口,但是这样您就不必在两者之间进行任何类型的映射

IQueryable<FlowerPetal> query1 = flowerContext.Flowers
    .Where(f => f.FlowerId == flowerId)
    .Join(flowerContext.Petals,
        f => f.PetalId,
        p => p.PetalId,
        (f, p) => new FlowerPetal { Flower = f, Petal = p }
    );

IQueryable<FlowerPetalClient> WithClients(IQueryable<FlowerPetal> _query, IQueryable<IClient> _clients) =>
    _query.SelectMany(
        x => _clients.Where(c => c.FlowerId == x.Flower.FlowerId).DefaultIfEmpty(),
        (x, c) => new FlowerPetalClient { Flower = x.Flower, Petal = x.Petal, Client = c }
    );

IQueryable<IClient> clients = useFlowerClients // decide on which client to use
    ? flowerContext.FlowerClients
    : flowerContext.AnotherClients;
var query = WithClients(query1, clients); // expand on query

您应该编写两个查询,用
if
/
else
分隔。这可能是最具可读性的。
class FlowerPetal
{
    public Flower Flower { get; set; }
    public Petal Petal { get; set; }
}
class FlowerPetalClient
{
    public Flower Flower { get; set; }
    public Petal Petal { get; set; }
    public IClient Client { get; set; }
}