检查实体框架中是否存在对象的最佳方法?

检查实体框架中是否存在对象的最佳方法?

问题描述:

从性能的角度来看,检查数据库中是否存在对象的最佳方法是什么?我使用的是实体框架 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