0

我有一个项目的问题。我正在尝试获取位于特定国家或城市的公司列表。

表结构:

公司

CompanyID
CompanyName
etc…

CompanyAddressDetails(关系表)

Company_CompanyID
CorrespondingAddress_AddressID

对应地址

AddressID
StreetName
RegionID
etc…

地区

RegionID
RegionName
RegionRegionTypeID

RegionDetails(关系表)

RegionParent
RegionChild

因此,要在示例 Stockholm 中找到一个地址(在 Region 表中的 ID 为 1198),我会这样做:

var addresses = from c in db.CorrespondingAddress select c;
addresses = addresses.Where(s => s.RegionID.Equals(1198));

要在斯德哥尔摩找到一家公司,我会这样做:

companyModel = from c in db.Company select c;
companyModel =  companyModel.Where(s => s.CorrespondingAddress.Any(x => x.RegionID.Equals(1198)));

但现在我想考虑 RegionDetails 表(它有一个父和子,例如:1(瑞典)是父,1198(斯德哥尔摩)是子等)

如何找到位于瑞典但地址行中 ID 为 1198(斯德哥尔摩)的公司?

在普通的 SQL 中,我可能会做类似的事情:

SELECT CompanyName FROM Company
LEFT JOIN CompanyAddressDetails ON (Company.CompanyID = CompanyAddressDetails.Company_CompanyID)
LEFT JOIN CorrespondingAddress ON (CompanyAddressDetails.CorrespondingAddress_AddressID = CorrespondingAddress.AddressID)
LEFT JOIN Region ON (CorrespondingAddress.RegionID = Region.RegionID)
WHERE CorrespondingAddress IN (SELECT RegionChild FROM RegionDetails WHERE RegionParent = 1)
4

2 回答 2

0

由于没有详细信息表(多对多关系表)的模型,因此我使用以下方法解决了它:

companyModel = companyModel.Where(s => s.CorrespondingAddress.Any(x => x.Region.RegionParent.Any(d => d.RegionID == region)));
于 2012-09-11T08:40:48.273 回答
0

首先,以下代码可以重构为一行:

companyModel = from c in db.Company select c;
companyModel =  companyModel.Where(s => s.CorrespondingAddress.Any(x => x.RegionID.Equals(1198)));

你不能再嵌套一个Any吗?

companyModel = db.Company.Where(s => s.CorrespondingAddress.Any(x => x.Region.Any(r => r.RegionDetails.Any(rd => rd.Parent == 1 && rd.Child == 1198)));

编辑

给定 的以下性质CorrespondingAddress

public virtual Region Region { get; set; } 

并假设Region有一个属性 RegionDetails (使 Region -> RegionDetails 一对一):

public virtual RegionDetails RegionDetails{ get; set; } 

以下应该有效:

companyModel = db.Company.Where(s => s.CorrespondingAddress.Any(x => x.Region.RegionDetails.RegionParent == 1 && x.Region.RegionDetails.RegionChild == 1198)));
于 2012-09-10T13:04:33.243 回答