检查实体框架中是否存在对象的最佳方式? [英] Best way to check if object exists in Entity Framework?

查看:121
本文介绍了检查实体框架中是否存在对象的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于检查实体框架中是否存在对象的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆