views:

60

answers:

2

I'm trying to do this with LINQ:

SQL>>    SELECT p_Id from items WHERE p_Name = 'R1'


LINQ>>   var getpID = (from p in myDatabaseDataSet.Items
                         where p.p_Name == ptxtBox.Text
                         select p.p_Id).SingleOrDefault();

            int p_Id = getpID;

But getpID always return 0. What's wrong?.

Edit: nvm the syntax is correct. Reason why it always returned 0 is the value doesn't exist in the db. I had the txt box value inserted in the db and then was trying to call it again before refreshing myDatabaseSet. So I needed to add Fill() and then getpID is able to read the value.

Full code:

        int c_Id = Convert.ToInt32(pcomboBox.SelectedValue);

        int p_Id = 0;
        string itemName = ptxtBox.Text;


        this.Validate();
        this.itemsBindingSource.EndEdit();
        this.itemsTableAdapter.Insert(c_Id, itemName);
        this.myDatabaseDataSet.AcceptChanges();
        this.itemsTableAdapter.Fill(myDatabaseDataSet.Items);


            var getpID = (from p in myDatabaseDataSet.Items
                          where p.p_Name == itemName
                          select p.p_Id).SingleOrDefault();

            p_Id = getpID;
+1  A: 

SingleOrDefault() -

Returns the only element of a sequence, or a default value if the sequence is empty;

It seems that your collection is empty(default if int is 0), check the ptxtBox.Text value

Svetlozar Angelov
+2  A: 

Instead of SingleOrDefault() use FirstOrDefault()

In case of the resulting sequence having multiple values SingleOrDefault() will fail to behave as you want, where are FirstOrDefault() will work.

Thanks

Mahesh Velaga
+1 I didn't know that behaviour. Thanks for the information!
Will Marcouiller
Actually if the sequence has multiple values, SingleOrDefault will throw an InvalidOperationException.
Ian Nelson
@Ian: corrected, Thanks!
Mahesh Velaga