[英]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. 我如何从数据库中获取最新的“ id”并将其放在文本框中注意:我必须从数据库中返回最新的id。
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);
}
You should handle when you have no record because Max
will throw InvalidOperationException
. 没有记录时应该处理,因为Max
会抛出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
}
Assuming that id
is stored as int and latest means largest id , you can simply use Max()
* : 假设id
存储为int并且Latest表示最大的id ,则可以简单地使用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. *)添加了DefaultIfEmpty(0)
以在query
没有结果的情况下返回0
。
Try this please. 请尝试这个。
var query = from t in table orderby t.Id descending
select t.Id;
object result = query.FirstOrDefault();
Hope helps. 希望会有所帮助。
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! 如果您要尝试做我想做的事情(将某些内容插入数据库,然后查询该数据库以查找您认为是刚刚插入的ID),那么请停止! 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). 这样做不会确保您检索到的ID是您需要的ID,因为数据库可以随时被其他人更改(并发)。 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: 但是,考虑到这只是一个测试,只有您使用它,并且您需要知道刚刚插入的ID,然后执行此操作的方法是:
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. 假设您使用LINQtoSQL或Entity Framework,则在将对象添加到上下文并调用SaveChanges()时,紧接着此对象将填充其ID(或主键)字段。 Just check! 只是检查!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.