Mustafa_K
Mustafa_K

Reputation: 95

How can I get data from my database in LINQ C#?

how can i get latest "id" from my database and put this in textbox note: i have to return latest id from my database.

look at this method :

public void refresh()
{
    var query = from qc in db.tbl_viewClients select qc.id  ;
    int a = Convert.ToInt32(query.SingleOrDefault().ToString());
    txt_id.Text = Convert.ToString(a);
}

Upvotes: 1

Views: 81

Answers (4)

iuliu.net
iuliu.net

Reputation: 7145

If you are trying to do what I think you are (inserting something into the database, and then querying it to find what you think is the just-inserted-ID), then stop! Doing this will not ensure that the ID you retrieve is the one you need, as your database can, at any time be changed by someone else (concurrency). But still, considering it's just a test, and it's just you who use it and you need to know the ID you just inserted, then the way to do this is:

Assuming you use LINQtoSQL or Entity Framework, when you add an object to the context and call SaveChanges(), right after this the object in question will have its ID (or primary key) field populated. Just check!

Upvotes: 1

har07
har07

Reputation: 89305

Assuming that id is stored as int and latest means largest id, you can simply use Max()* :

int a = query.DefaultIfEmpty(0).Max();

Otherwise, information to determine latest, such as creation date, is missing from the question.

*) added DefaultIfEmpty(0) to return 0 in case query return no result.

Upvotes: 1

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

Try this please.

var query = from t in table orderby t.Id descending
                    select t.Id;

object result =  query.FirstOrDefault();

Hope helps.

Upvotes: 1

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

You should handle when you have no record because Max will throw InvalidOperationException.

var query = from qc in db.tbl_viewClients select qc.id;
if (query.Any())
{
    var max = query.Max();
    txt_id.Text = max.ToString();
    // do rest of work
}
else
{
   //handle the case when you have no record
}

but this approach enumerates the query twice!
Here is a trick!

var query = from qc in db.tbl_viewClients select (int?)qc.id;
var max = query.Max();
if (max.HasValue)
{
    txt_id.Text = max.ToString();
    // do rest of work
}
else
{
    //handle the case when you have no record
}

Upvotes: 2

Related Questions