我目前正在尝试检查SQL表中是否存在具有唯一ID的对象的实例。以免重复。以下是我目前的样本:
string ui = someObj.getUniqueID();
IQueryable<String> checkDataQuery = from cdq in db.SomeObjects
where cdq.UniqueID == ui
select cdq.UniqueID;
if (checkDataQuery != ui) // This is just my attempt at making sure that
// the query actually returned something and not
// the string representing nothing found, so if there
// is a better checking method that would even more helpful.
我遇到的主要问题是我无法以checkDataQuery
的身份访问string
。我尝试使用.Single()/.First()
方法进行转换,然而前者没有成功,后者使单个字符串返回到字符列表中。
答案 0 :(得分:2)
您可以使用Enumerable.Any
检查结果,如:
bool ifExists = db.SomeObjects.Any(r=> r.UniqueID == ui);
如果您想获取该对象,则可以使用FirstOrDefault
并检查null
,如:
var dbObject = db.SomeObjects.FirstOrDefault(r=> r.UniqueID == ui);
if(dbObject != null)
{
//record exists
}