简体   繁体   中英

What is the best way to determine if table already has record with specific 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?

Thanks in advance.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM