简体   繁体   中英

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.

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

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

做这个 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM