Katerina
Katerina

Reputation: 364

Query not returning anything

I have 2 tables: winery and wineType (in wineType I have foreign key for winery, called wineryID). I try get all winery names that produce wine like the one the client selected from drop down list. And I have this function

public void ispolniLista()
{
    DataClassesDataContext MyDB = new DataClassesDataContext();
    var id = from wineT in MyDB.WineTypes where wineT.kind == ddlSorti.SelectedItem.Text select new { wineT.wineryID };

     List<int> listaID = id as List<int>;
     List<string> listaIminja = new List<string>();
     try
     {
         foreach (int i in listaID)
         {
             var vname = from w in MyDB.Wineries where w.wineryID == i select new { w.name };
             listaIminja.Add(vname.ToString());
         }
         lstVinarii.DataSource = listaIminja;
         lstVinarii.DataBind();
     }
     catch (NullReferenceException err)
     {
         Console.Write(err.Message);
     }
 } 

And I have nothing for result, the lstVinarii is empty.

Upvotes: 1

Views: 100

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176896

EDIT

Note: From your code Remove new from select, no need to create extra anonymous type that is also one problem

To avoid comment error write like this

  var id = from wineT in MyDB.WineTypes 
where wineT.kind == ddlSorti.SelectedItem.Text 
select wineT.wineryID ;

Remove new from select, no need to create extra anonymous type same in below code


try

List<int> listaID = id.ToList<int>(); 

than remove foreach loop and write like this

var listaIminja= (from win MyDB.Wineries
             where listaID .Contains( w.wineryID ) 
            select  w.name ).ToList();
      lstVinarii.DataSource = listaIminja;
      lstVinarii.DataBind();

Upvotes: 1

Willie van Doren
Willie van Doren

Reputation: 79

List<int> id = ( from wineT in MyDB.WineTypes where wineT.kind == ddlSorti.SelectedItem.Text select  wineT.wineryID ).ToList();

Do this !

Upvotes: 2

Matt Whitfield
Matt Whitfield

Reputation: 6574

Where you are casting the result like this:

List<int> listaID = id as List<int>;

You need to instantiate it so the enumerable is actually enumerated, like this:

List<int> listaID = new List<int>(id);

However, it would be worth re-writing this to take advantage of joins, because you're going to be popping off a lot of queries with the method above (because you have a query within a loop).

Upvotes: 2

Related Questions