Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get single value by using entity framework

I have a

     table product with colums product_id 
                               prodcut_name
                               category_id

                another table  category 
                               category_id
                               category_name

and i am populating these product details using datagridview that working fine

and i need to get the categoryname for selected row in datagridview for that i have done like this....

        private void productGridview_Cellclick(object sender, DataGridViewCellEventArgs e)
        {
               string productname = Convert.ToString(selectedRow.Cells["productnam"].Value);
               var categoryids = from cats in abc.products
                                where cats.product_Name.Equals(productname)
                                select cats.category_Id;


            var catogynames = from categorytypes in abc.categories
                              where categorytypes.category_Name.Equals(categoryids)
                              select categorytypes.category_Name;


            string categorynames = catogynames;    

       }                              

got an

  error : cannot implicitly convert type sysytem.linq.iqueryble<string> to string ...

what i need to do to get the single category name for selected cell in productgridview productnam column

any suggestions.. pls ..

many thanks....

Modified Code: got an error :

not supported exception:

Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
like image 351
Glory Raj Avatar asked Aug 19 '11 11:08

Glory Raj


1 Answers

Your query is returning a query object that behaves like a collection. You can use First, FirstOrDefault, Single, or SingleOrDefault to retrieve the first or single item from the query respectively.

var categoryid = (from cats in abc.products
                  where cats.product_Name.Equals(productname)
                  select cats.category_Id).SingleOrDefault();


string categoryname = (from categorytypes in abc.categories
                       where categorytypes.category_Name.Equals(categoryid)
                       select categorytypes.category_Name).SingleOrDefault();
like image 183
Dennis Traub Avatar answered Oct 10 '22 05:10

Dennis Traub