简体   繁体   中英

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

您有查询,但是对于绑定您需要数据,请尝试以下操作

dataGridView2.DataSource = data.ToList();

just add .ToList()

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

dataGridView1.DataSource = data;
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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM