检查实体框架中是否存在对象的最佳方式?
问题描述:
从性能的角度来说,检查数据库中是否存在对象的最佳方式是什么?我正在使用Entity Framework 1.0(ASP.NET 3.5 SP1)。
What is the best way to check if an object exists in the database from a performance point of view? I'm using Entity Framework 1.0 (ASP.NET 3.5 SP1).
答
如果不想直接执行SQL最好的方法是使用 Any()。这是因为Any()将在找到匹配后立即返回。另一个选项是 Count(),但这可能需要检查每一行在返回之前。
If you don't want to execute SQL directly, the best way is to use Any(). This is because Any() will return as soon as it finds a match. Another option is Count(), but this might need to check every row before returning.
这是一个如何使用它的例子:
Here's an example of how to use it:
if (context.MyEntity.Any(o => o.Id == idToMatch))
{
// Match!
}
而在vb.net中
If context.MyEntity.Any(function(o) o.Id = idToMatch) Then
' Match!
End If