我必须遵循以下方案:
公司可以有多个地址,每个地址都有一个邮政编码。 客户通过邮政编码搜索,结果应该是10英里范围内的所有公司。 公司地址可以在许多不同的位置,我只想返回10英里范围内的1。
我需要一个linq查询来获取公司,并且只需要他们在10英里范围内拥有的地址。我不希望他们的其他地址超出半径。
这是我已经拥有但它返回所有地址,甚至是半径以外的地址:
var distanceMeters = distanceMiles * 1609.34d; //the distance
DbGeography geo = GetGeoLocationByPostcode(postalCode.Replace(" ", "")); //gets the geo for the query
//Attempt 1
return (from m in context.Company
let ma = context.Addresses.OrderBy(ma2 => m.ID == ma2.CompanyId && ma2.Location.Distance(geo) <= distanceMeters)
orderby ma.Location.Distance(geo)
select m).Take(items).ToList();
//Attempt 2
return (from m in context.Company
join ma in context.Addresses on m.ID equals ma.CompanyId
orderby ma.Location.Distance(geo)
where ma.Location.Distance(geo) <= distanceMeters
select m).Take(items).ToList();
//Attempt 3
return (from m in context.Company
from ma in context.Addresses.Where(o => o.CompanyId == m.ID && o.Location.Distance(geo) <= distanceMeters).ToList().Take(1)
orderby ma.Location.Distance(geo)
select m).Take(items).ToList();
所以我来问专家,因为我是一个老式的SQL存储过程家伙,因为我正在学习使用EF6的linq我不断遇到我只能在TSQL中编写的查询但这个linq的东西很难让我的头,任何帮助非常感谢。 TKS
答案 0 :(得分:0)
试试这个:
var result = context.Adresses.Where(x => context.Company.Id = x.CompanyId && x.Location.Distance(geo) <= distanceMeters).ToList()
**这是未经测试的,但我希望这会给你一些想法;)!
答案 1 :(得分:0)
lookUp很快:
var context_lookup_byID = context.Adresses.ToLookUp(p=>p.CompanyId);
var query = (from c in context.Company
select new
{
Name = c.CompanyName,
simpleAdress = context_lookup_byID[c.Id].Where(p=>p.Location.Distance(geo) <= distanceMeters).OrderBy(p=>p.Location.Distance(geo)).FirstOrDefault(null)
}).Take(numbers);
foreach(var q in query)
{
Console.Write(q.Name + " ");
bool notFound = q.simpleAdress == null;
if(notFound)
Console.Write("not found any address");
else
Console.Write("Nearest adress: " + q.simpleAdress.Adress);
}
我接受那个数据context.Company有属性Name(string)和context.Adressess有属性Adress(string)