什么是确定的表已经与特定ID记录的最好方法? [英] What is the best way to determine if table already has record with specific ID?

查看:92
本文介绍了什么是确定的表已经与特定ID记录的最好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的问题。我使用LINQ到SQL即时通讯目前的任务。这是确定表中有特定ID记录的最好方法是什么?

I have a short question. Im my current project I'm using LINQ-to-SQl. That is the best way to determine if table has record with specific ID?

在此先感谢。

推荐答案

如果你只需要知道它的存在,那么也许:

If you just need to know if it exists, then perhaps:

var exists = db.SomeTable.Any(row => row.Id == id);

如果你想要的行(或,如果它不存在),则:

If you want the row (or null if it doesn't exist), then:

var row = db.SomeTable.FirstOrDefault(row => row.Id == id);

实际上,在.NET 3.5中存在可以说是<一个href="https://connect.microsoft.com/VisualStudio/feedback/details/362313/linq-to-sql-still-roundtrips-for-id-lookups-3-5sp1"相对=nofollow>一个好处使用:

var row = db.SomeTable.Where(row => row.Id == id).FirstOrDefault();

但这是固定在4.0和两个工作相同。所不同的是,在3.5SP, FirstOrDefault(predicate)不检查身份管理器,所以它会击中分贝,即使它已经知道有关行,你问的(因为它有它的内存)。

but this is fixed in 4.0 and both work the same. The difference is that in 3.5SP, FirstOrDefault(predicate) doesn't check the identity-manager, so it would hit the db even if it already knows about the row you asked for (because it has it in-memory).

这篇关于什么是确定的表已经与特定ID记录的最好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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