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?

gsiradze
  • 4,583
  • 15
  • 64
  • 111

3 Answers3

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().

jjaskulowski
  • 2,524
  • 3
  • 26
  • 36
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();
        }
Kiran Hegde
  • 3,651
  • 1
  • 16
  • 14
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

Community
  • 1
  • 1
Arijit Mukherjee
  • 3,817
  • 2
  • 31
  • 51