[英]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. 在datagridview2中,它不显示数据,但是当我重新启动程序时。 One and Two tables contain a relationship between One.ID -> Two.OID
一表和二表包含One.ID-> Two.OID之间的关系
您有查询,但是对于绑定您需要数据,请尝试以下操作
dataGridView2.DataSource = data.ToList();
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
. 除非您调用
.Count()
或.ToList()
类的.Count()
称为Deferred Execution
.ToList()
,否则该语句将不会Deferred Execution
。 Take a look at the table in this article
, and you'll see the classifications of the operators. look at the table in this article
,您将看到运算符的分类。
To get the latest, may want to look at using the OrderByDescending
. 要获取最新版本,可能需要使用
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
? 您是否希望
dataGridView2
使用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();
调用
dataGridView.DataBind();
method after assigning the data. 分配数据后的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.