LINQ - 嵌套(地址和城市)查询

时间:2012-09-10 12:50:26

标签: linq entity-framework

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

表格结构:

公司

CompanyID
CompanyName
etc…

CompanyAddressDetails (关系表)

Company_CompanyID
CorrespondingAddress_AddressID

CorrespondingAddress

AddressID
StreetName
RegionID
etc…

区域

RegionID
RegionName
RegionRegionTypeID

RegionDetails (关系表)

RegionParent
RegionChild

所以为了在示例斯德哥尔摩(在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)

2 个答案:

答案 0 :(得分: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)));

答案 1 :(得分:0)

因为没有详细信息表的模型(多对多关系表),所以我使用这种方法解决了它:

companyModel = companyModel.Where(s => s.CorrespondingAddress.Any(x => x.Region.RegionParent.Any(d => d.RegionID == region)));