实体框架新手,我需要连接 4 个表,但其中一个表与其他 3 个表上的任何列均不相关(通过名称或引用)。
这些是我的课程/桌子:
Locations {
id
platId
}
Plat {
id
}
Settings {
id
platId
enabledCol
}
ExternalData {
vId // Same id as Plat.id, Locations.PlatId, and Settings.PlatId
enabled (bool)
}
截至目前,我有这个:
db.Locations
.Include(l => l.Plat)
.ThenInclude(p => p.Setting)
.Where(l => l.Active == true && l.Plat.Setting.enabledCol == true)
.ToList()
但不知道如何包含
extenralData
说: where (Plat.Id ==ExternalData.vId OR Locations.PlatId == vId)
为现有查询集分配一个值,如下所示:
var result = db.Locations
.Include(l => l.Plat)
.ThenInclude(p => p.Setting)
.Where(l => l.Active == true && l.Plat.Setting.enabledCol == true)
.ToList();
然后您可以单独查询
ExternalData
表并根据 result
查询中的值对其进行过滤:
var externalDataResult = db.ExternalData
.Where(ed =>
result.Any(r => r.Plat.Id == ed.vId) ||
result.Any(r => r.PlatId == ed.vId))
.ToList();
如果您需要保存在同一列表中的所有表中的所有数据,您可以继续连接每个表并从每个表中创建新对象:
var result = db.Locations
.Join(db.Plat, l => l.PlatId, p => p.id, (l, p) => new { Location = l, Plat = p })
.Join(db.Settings, lp => lp.Plat.id, s => s.platId, (lp, s) => new { LocationPlat = lp, Setting = s })
.ToList()
.Where(x => x.LocationPlat.Location.Active && x.Setting.enabledCol)
.Join(db.ExternalData,
lp => new { Id = lp.LocationPlat.Plat.id, LocationPlatId = lp.LocationPlat.Location.PlatId },
ed => new { Id = ed.vId, LocationPlatId = ed.vId },
(lp, ed) => new { LocationPlatSetting = lp, ExternalData = ed })
.ToList();