什么是确定的表已经与特定ID记录的最好方法?方法、ID

2023-09-04 23:22:07 作者:瞎子都夸俺长的帅

我有一个简短的问题。我使用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中存在可以说是一个好处使用:

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).

 
精彩推荐
图片推荐