utilizing entity framework to obtain a single value

c# entity-framework linq linq-to-entities winforms


I have a

     table product with colums product_id 

                another table  category 

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.
7/23/2015 4:59:53 PM

Accepted Answer

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();
8/19/2011 11:30:55 AM

Popular Answer

your problem with casting is here

  string categorynames = catogynames;

catogynames is IQueryble. You can do something like this,

List<String> categorynames = catogynames.ToList();

Or you can iterate through catogynames.

P.S please review your variable names :D.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow