0

I'm trying to retrieve information from ms sql server to my div.

<div id="blablablaText" runat="server">
                    ...
                </div>

and here's my source code

 protected void Page_Load(object sender, EventArgs e)
    {
        using (myDbDataContext wdb = new myDbDataContext ())
        {
            Article ar = new Article();

            var a = from p in wdb.Articles
                    where p.Id == 16
                    select p.Text;



            blablablaText.InnerText = a.ToString();
        }
    }

after that my output is:

SELECT [t0].[Text] FROM [dbo].[Article] AS [t0] WHERE [t0].[Id] = @p0

what am I doing wrong?

2
  • 1
    try a.First() instead of a.ToString(). Commented Jul 3, 2014 at 9:57
  • @George First() is not the right way of doing it Commented Jul 3, 2014 at 10:00

3 Answers 3

1

You want to execute .First() on that instead of .ToString();

a is a query. First() will execute it and return the value of first row of the executed sql select statement. As you selected only one string column a will already be the string you want.

Beware. First() must find at least one row or it will throw an exception. If you want to get null in the worst case scenario then you should use FirstOrDefault().

Sign up to request clarification or add additional context in comments.

Comments

0

You have to to get the first or firstordefault before converting to string

using (myDbDataContext wdb = new myDbDataContext ())
        {
            Article ar = new Article();

            var a = from p in wdb.Articles
                    where p.Id == 16
                    select p.Text;



            blablablaText.InnerText = a.First().ToString();
        }

Comments

0
using (myDbDataContext wdb = new myDbDataContext ())
    {
        Article ar = new Article();

        var a = (from p in wdb.Articles
                where p.Id == 16
                select p.Text).FirstorDefault();



        blablablaText.InnerText = a.ToString();
    }

Your should be using FirstorDefault() instead of First(); as If there is nothing in your variable a then First will throw an exception where as FirstorDefault will set it to null/empty.

First VS FirstorDefault

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.