views:

47

answers:

1

Hello.

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?

Thanks in advance.

+3  A: 

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

actually, in .NET 3.5 there is arguably a benefit to using:

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

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

Marc Gravell
Marc, thanks for detailed answer.
iburlakov