views:

62

answers:

2

For example, imagine that I want to see if a user exists in my database:

Select * from Users where inputID = Users.ID

Then if that result brought > 0 items, then the user exists, correct?

How can I do something like this using a pure Linq-to-SQL class?

+1  A: 
var user = dbContext.GetTable<User>().SingleOrDefault(u => u.ID == inputID);
bool userExists = user != null;

That will fetch the matching user from the database, if you just want to check for existance you can do this:

int matchingUsers = dbContext.GetTable<User>().Count(u => u.ID == inputID);
bool userExists = matchingUsers > 0;

or

bool userExists = dbContext.GetTable<User>().Any(u => u.ID == inputID);
Lee
I have never seen the `GetTable<>` method before. What is the difference between `dbContext.GetTable<User>()` and `dbContext.Users`? Thanks.
Deniz Dogan
@Deniz Dogan - GetTable is defined on the DataContext class, if you use the linq2sql designer to create entity classes then it creates a subclass of DataContext and defines a property for each db-mapped type. So in this case it will look like `IQueryable<User> Users { get { return this.GetTable<User>(); }}`
Lee
Ah, I see. So the two ways are basically identical. Cool. :)
Deniz Dogan
+6  A: 
dbContext.Users.Any(x => x.ID == inputID)
Deniz Dogan
+1. This results in the most efficient database query.
Steven
Thank you this works beautifully! :)
Sergio Tapia