Result from Linq query to ASP Literal?
-
Saturday, October 06, 2012 6:34 PM
Good morning-
I have a couple of values I want to display on an ASP.NET page in asp:Literal fields. My problem is that when tested, it only displays the SQL query, not the results.
Here's my code:
var queryPrice = from price in db.D_Items where price.ItemId == itemId select new { price.Price }; PriceLiteral.Text = queryPrice.ToString(); var queryQuantity = from quantity in db.F_ShoppingLists where quantity.MemberId == custId && quantity.ItemId == itemId select new { quantity.Quantity }; var queryItemSelected = from items in db.D_Items where items.ItemId == itemId select new { items.ItemName }; ItemSelectedLiteral.Text = queryItemSelected.ToString();And here is the output on the page:
Item Selected: SELECT [t0].[ItemName] FROM [dbo].[D_Item] AS [t0] WHERE [t0].[ItemId] = @p0 Price: SELECT [t0].[Price] FROM [dbo].[D_Item] AS [t0] WHERE [t0].[ItemId] = @p0
I want it to look like:
Item Selected: RAM chip (2GB DDR3) Price: $41.14
What am I doing wrong here? I've become frustrated, so my searching skills have gone down significantly...
Thanks in advance.
Kyle Masters
Business and Financial Intelligence Analyst - Firewind Digital Studios
Contributor - The SQL School
All Replies
-
Sunday, October 07, 2012 3:57 PM
When you use the ToString method in a query you will get the SQL that would be sent to the server.
Each query in L2S will return a set of items. This set can be empty, a single item or many items. In your first query you will receive from the query (assuming that itemId identifies a unique D_ITem) a single "Price" or nothing if the D_Item does not exist. To handle this you will want to use the SingleOrDefault method to return just one item or NULL. Then your ToString will work fo the first query.
You will have the same problem with each of your queries but the above should fix your problem.
Hope this helps
Lloyd Sheen
Lloyd Sheen
-
Sunday, October 07, 2012 4:07 PM
Hi Kyle_Masters;
A Linq query is a query that is not executed until it is enumerated over or use a method which enumerates the query. to get the following to bring back the results from the database you can do the following.var queryPrice = (from price in db.D_Items where price.ItemId == itemId select new { price.Price }).FirstOrDefault(); PriceLiteral.Text = queryPrice.ToString();
Using the FirstOrDefault method will enumerate the query and return the first item or a default value for the data type being returned.
Fernando (MCSD)
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Marked As Answer by Kyle_Masters Sunday, October 07, 2012 7:55 PM

