Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq query one to one

trying to get the concert name, date and venue (which is stored on another table) but it doesn't seem to be working, but it keeps pulling back null.

var test = from f in db.Concert
           where f.Name.StartsWith(concertName)
           select new
           {
               f.Name,
               f.StartDateTime,
               venues = from v in db.Venues
                        where v.ID == f.VenueID
                        select v.Address
           }

Edit:

The relationship between Venue and Concert is that Concert has a VenueID that relates to the Venue ID. I need to pass a string back. something like

foreach (var e in test)
{
   html += "<div> e.Name +":" + e.Address </div>;
}
like image 212
datatest Avatar asked Jan 14 '13 18:01

datatest


People also ask

How do I return a single value from a list using LINQ?

var fruit = ListOfFruits. FirstOrDefault(x => x.Name == "Apple"); if (fruit != null) { return fruit.ID; } return 0; This is not the only road to Rome, you can also use Single(), SingleOrDefault() or First().

What does .select do in C#?

In a query expression, the select clause specifies the type of values that will be produced when the query is executed. The result is based on the evaluation of all the previous clauses and on any expressions in the select clause itself. A query expression must terminate with either a select clause or a group clause.

How does a LINQ query transform to a SQL query?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.


2 Answers

You can use group join to get all Venues related to Concert

var test = from f in db.Concert
           join v in db.Venues on f.VenueID equals v.ID into g
           where f.Name.StartsWith(concertName)
           select new
           {
               f.Name,
               f.StartDateTime,
               Venues = g.Select(x => x.Address)
           };

Usage of results:

foreach (var e in test)
{
   // e.Name
   // e.StartDateTime

   foreach(var address in e.Venues)
      // address
}
like image 144
Sergey Berezovskiy Avatar answered Oct 11 '22 17:10

Sergey Berezovskiy


It looks like it's safe to assume a 1:1 relationship between Concerts and Venues. Given that, you can use join instead.

var test = from f in db.Concert
           join v in db.Venues on v.ID equals f.VenueID
           where f.Name.StartsWith(concertName)
           select new
           {
               f.Name,
               f.StartDateTime,
               v.Address
           };
like image 39
Austin Salonen Avatar answered Oct 11 '22 18:10

Austin Salonen