sql server -在3个表连接或一个表没有键关系的情况下产生c#对实体(EF)查询的问题
本文关键字:情况下 关系 查询 问题 EF 实体 3个 server 连接 sql 一个 | 更新日期: 2023-09-27 18:02:13
一直在尝试一堆东西,但不能得到任何工作的实体框架。表结构:
Device DeviceLegacy BillingDeviceProduct
------ ------------ --------------------
ID DeviceID SKU = 123
Num LegacyID NID
Name LegacyUID SID
(省略多余字段)
DeviceLegacy。DeviceID是Device.ID的外键关系。DeviceLegacy和BillingDeviceProduct在数据库中没有关系,但是如果DeviceLegacy有一个BillingDeviceProduct (SKU=123), LegacyID将等于NID或LegacyUID将等于SID。有时这两个值会匹配。有时它们不匹配,但其中一个总是匹配的。
SQL:select Num, Name from BillingDeviceProduct bdp
join DeviceLegacy leg on leg.LegacyUID = bdp.SID or leg.LegacyID = bdp.NID
join Device on Device.id = leg.DeviceID
where SKU = 123
当DeviceLegacy和BillingDeviceProduct两个值都不匹配时,我们有以下代码:
from device in Devices
join dlegacy in DeviceLegacies
on device.ID equals dlegacy.DeviceID
into dl
from devicelegacy in dl
join bdproduct in BillingDeviceProducts
on new { devicelegacy.LegacyID, devicelegacy.LegacyUID } equals new { LegacyID = bdproduct.NID, LegacyUID = bdproduct.SID }
into bdp
from deviceproduct in bdp
where deviceproduct.SKU == 123
select new { device.Num, device.Name}
似乎可以使用外键关系至少排除一个连接
from bdp in BillingDeviceProducts
where bdp.SKU = 123
from dl in DeviceLegacies.Include("Device")
where (bdp.SID == dl.LegacyUID || dbp.NID == dl.LegacyID)
select new {
Num = dl.Device.Num,
Name = dl.Device.Name
}