Rabee Alrabee
Rabee Alrabee

Reputation: 105

Get the last inserted data in Linq

How can I get recent data that has been inserted into the database?

I'm using the following code to insert:

DB.One one = new DB.One();
one.Name = "Name";

db.One.InsertOnSubmit(one);
db.SubmitChanges();

DB.Two two = new DB.Two();
two.OID = one.ID;
two.Age = 20;

db.Two.InsertOnSubmit(two);
db.SubmitChanges();

When I query about the data I use:

var data = from d in db.One
           where d.Name.Contains(textBox1.Text.Trim())
           select d;

dataGridView1.DataSource = data;

dataGridView2.DataSource = data;
dataGridView2.DataMember = "Two";

In datagridview2 it does not display the data, but when I restart the program. One and Two tables contain a relationship between One.ID -> Two.OID

Upvotes: 1

Views: 243

Answers (4)

Igor Ševo
Igor Ševo

Reputation: 5495

Call dataGridView.DataBind(); method after assigning the data.

Upvotes: 0

Christian Phillips
Christian Phillips

Reputation: 18749

var data = from d in db.One
           where d.Name.Contains(textBox1.Text.Trim())
           select d;

This statement, will not be executed until you call something like .Count() or .ToList(), this is known as Deferred Execution. Take a look at the table in this article, and you'll see the classifications of the operators.

To get the latest, may want to look at using the OrderByDescending.

var data = from d in db.One.OrderByDescending(d => d.DateAdded);//for example

EDIT: Based on your update

Do you want dataGridView2 to use db.Two?

var data = (from d in db.One
           where d.Name.Contains(textBox1.Text.Trim())
           select d).ToList();

var data2 = (from d in db.Two
           where d.Name.Contains(textBox1.Text.Trim())
           select d).ToList();

dataGridView1.DataSource = data;
dataGridView2.DataSource = data2;

Upvotes: 0

spajce
spajce

Reputation: 7082

just add .ToList()

var data = (from d in db.One
           where d.Name.Contains(textBox1.Text.Trim())
           select d).ToList();

dataGridView1.DataSource = data;

Upvotes: 1

Damith
Damith

Reputation: 63065

you have query, but for the binding you need to have the data, try below

dataGridView2.DataSource = data.ToList();

Upvotes: 1

Related Questions