我正在尝试编写LINQ查询,其中我要根据前端发回的内容访问两个不同表中的数据
如果FlowerClients
是从前端发送的,我想使用FlowerClient
表,或者如果要发送的数据是用于AnotherClient
的,请使用AnotherClient。
这是否可以在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()
答案 0 :(得分:0)
您可能想要创建不同的方法,尤其是在FlowerClients
和AnotherClients
类非常不同的情况下。
否则,您可以动态生成查询表达式。您可能要确保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
带有一些帮助程序类:
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; }
}