通过拥有linq到sql组

时间:2009-05-15 00:04:06

标签: linq linq-to-sql

任何人都可以向我展示如何使用linq to sql来编写查询 搜索在特定州至少有1个地点的郊区

位置

SuburbID
SuburbName
StateName

地点

VenueID
VenueName
SuburbName
StateName

2 个答案:

答案 0 :(得分:2)

var locations = from loc 
                in dataContext.Locations 
                where loc.Venues.Count > 1 
                select loc

编辑:最终答案:

如果您在位置/地点之间设置了外键:

string stateName = "New York";  

var locations = from loc 
                in dataContext.Locations 
                where loc.Venues.Count > 1 && loc.StateName == stateName 
                select loc;

如果没有外键关系:

string stateName = "New York";

var locations = (from v 
                 in dataContext.Venues 
                 where v.StateName == stateName 
                 select (from l 
                         in dataContext.Locations 
                         where l.SuburbName == v.SuburbName && l.StateName == v.Statename              
                         select l
                        ).Single()).Distinct();

真的,你应该修好你的桌子。 Venue表应该有一个suburbID而不是“StateName”和“SuburbName” - 保留两者是多余的。

答案 1 :(得分:0)

以下是几个简单的答案:

var suburbNames = dataContext.Venues
  .Where(v => v.StateName == specificState)
  .GroupBy(v => v.SuburbName)
  .Select(g => g.Key)

           //

var locations = dataContext.Location
  .Where(loc => loc.StateName == specificState)
  .Where(loc => loc.Venues.Any())

使用Venues属性:您可以通过将linq中的关系添加到sql设计器来实现 - 即使外键不存在/未在数据库中强制执行。