在LINQ结果集返回到SQL之前,检查存在的一个记录 [英] Check existence of a record before returning resultset in LINQ to SQL
问题描述
我正在寻找一个简单的解决方案,以取代在验证记录是否试图检索数据之前存在我的标准化垃圾的方式。目前,只要我的方法之一是所谓的,我做一些事来的效果...
I'm looking for a simple solution to replace my standardized junk way of validating whether a record exists before attempting to retrieve the data. Currently, whenever one of my methods are called, I do something to the effect of...
private Record DoSomething(int id)
{
if(data.Records.Count(q=>q.Id==id) > 0)
{
return data.Records.First(q=>q.Id==id);
}
return null;
}
......,我总是检查记录的数量来确定记录的存在。必须有这样做的更优雅的方式,而不调用数据库的两倍。有什么办法?
...where I always check the count of the records to determine the existence of a record. There has to be a more "elegant" way of doing this, without calling the database twice. Is there a way?
推荐答案
有很多干净的方式来处理这个问题。如果你想第一个记录
对应 ID
你可以说:
There are a lot of clean ways to handle this. If you want the first Record
corresponding to id
you can say:
Record record = data.Records.FirstOrDefault(r => r.Id == id);
if(record != null) {
// record exists
}
else {
// record does not exist
}
如果您只想知道如果这样的记录
存在:
If you only want to know if such a Record
exists:
return data.Records.Any(r => r.Id == id); // true if exists
如果你想的数有多少这样的记录
存在:
If you want a count of how many such Record
exists:
return data.Records.Count(r => r.Id == id);
如果你想要一个枚举(的IEnumerable<记录>
)的所有这样的记录
:
If you want an enumeration (IEnumerable<Record>
) of all such Record
:
return data.Records.Where(r => r.Id == id);
这篇关于在LINQ结果集返回到SQL之前,检查存在的一个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!