【发布时间】:2021-03-22 17:12:48
【问题描述】:
在我使用 EF Core 5.0 的 C# 项目中,我有几个独立的表:Clothes、Hairs、Makeup。他们的一些列是相似的,但有些不是..`
我需要编写一个从这些表中加载行的方法。我现在拥有的是:
public async Task<(ClothesDbModel[] clothes, MakeupDbModel[] makeups, HairDbModel[] hairs)> GetDressup(int[] clothesIds, int[] makeupIds, int[] hairIds)
{
ClothesDbModel[] clothes = new ClothesDbModel[0];
if (clothesIds.Length > 0)
{
clothes = await _dbContext.Clothes.Where(c => clothesIds.Contains(c.Id)).ToArrayAsync();
}
MakeupDbModel[] makeups = new MakeupDbModel[0];
if (makeupIds.Length > 0)
{
makeups = await _dbContext.Makeups.Where(c => makeupIds.Contains(c.Id)).ToArrayAsync();
}
HairDbModel[] hairs = new HairDbModel[0];
if (hairIds.Length > 0)
{
hairs = await _dbContext.Hairs.Where(c => hairIds.Contains(c.Id)).ToArrayAsync();
}
return (clothes, makeups, hairs);
}
但是,在这种情况下,我对数据库有 3 个单独的查询(3 个等待)。从性能的角度来看,我认为这不是加载数据的最佳方式。也许我只能使用 DbContext 加载相同的数据一次&
【问题讨论】:
-
如果这些表互不依赖,那就没有办法了
-
您可能知道 EF 不支持 multiple parallel operations。您可以创建三个不同的
_dbContext。但是,由于开销可能不值得。 -
实际上可以使用
Concat做到这一点,但需要在客户端进行后处理。