views:

339

answers:

2

Could any one show my how to write query using linq to sql to search for suburbs which have at least 1 venue in specific state

Location

SuburbID
SuburbName
StateName

Venue

VenueID
VenueName
SuburbName
StateName
+1  A: 
var locations = from loc 
                in dataContext.Locations 
                where loc.Venues.Count > 1 
                select loc

EDIT: Final answer:

If you have the foreign keys setup between Location/Venue:

string stateName = "New York";  

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


If there isn't a foreign key relationship:

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();


Really though, you should fix your tables. The Venue table should have a suburbID instead of "StateName" and "SuburbName" - it is redundant to keep both.

I knew the table should have SuburbID however sometime user may enter suburb that not in the database yet?
If it isn't in the database yet then add it before inserting the Venue. Or make the user enter a new suburb before they can add a venue to it.
Suppose a user fully enters a Venue's information - at that point, you have enough information to store a Suburb. (unless there are fields we don't see).
David B
A: 

Here's a couple of simple answers:

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())

With that Venues property: you can get that by adding the relationship in the linq to sql designer - even if the foreign key doesn't exist / isn't enforced in the database.

David B