2

I was working with ASP.NET and I try to change a label text and get the value from data base. here is what i do.

First I add database then I create a linq and then I use query to load it but it won't work.

this is query code

protected void Page_Load(object sender, EventArgs e)
{
    DataClasses1DataContext db = new DataClasses1DataContext();
    var q = from dc in db.topboxes
            where dc.id == (1)
            select dc;
    Lmain11.Text = q.ToString();
}

this is image

and this is what I get as label text

SELECT [t0].[id], [t0].[title], [t0].[dc], [t0].[adminid] FROM [dbo].[topbox] AS [t0] WHERE [t0].[id] = @p0

this image

Can someone please tell me what should I do? It is not the value that I indented to print

and also when I want to get dc from database topbox where id = 1 I also try code without () in where line.

also my data is not null enter image description here

0

1 Answer 1

3

Linq queries return an IEnumerable<T> and you want to access a specific item in the collection, to a specific property. Use FirstOrDefault().

DataClasses1DataContext db = new DataClasses1DataContext();
var q = (from dc in db.topboxes
         where dc.id == 1
         select dc).FirstOrDefault();

Lmain11.Text = q?.SomeProperty;

FirstOrDefault might return default(T) if such was not found in query. In your case the default is null. Use C# 6 ?. operator to safely access the desired property

Using on a linq-2-sql query .ToString() will give you the sql that is being generated - Great when you want to see under the hood :)

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

21 Comments

thanks for answer, my data is something else but now it show me a text myprojectname.topbox is what i get.
@ArsalanAhmadi q can be null, if nothing in db.topboxes has an id of 1.
@GiladGreen I didn't think about second execution, now I check the reference code. Thanks +1, I learn something new.
No worries I was going to delete the answer anyway, it was stupid.
@mybirthname - BTW - awesome picture :P
|

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.