Tuesday, January 8, 2013

LINQ : How to check if a record exists in the database

Issue: How to check if a record exists in the database using LINQ

// Solution 1: Select . Don't use SingleOrDefault because if there are more than one record returned it throws exception.
var res = (from cls in db.Classrooms
                 where cls.Name == "10A"
                 select cls).SingleOrDefault();

                
if(res != null)
{
    //record exists
}

// Solution 2: Select Count if you don't want to load the entity. This is an efficient method but not the most efficient. The LINQ expression translates to Count(*) in SQL.
int res = (from cls in db.Classrooms
                 where cls.Name == "10A"
                 select cls).count();
                
if(res > 0)
{
    //record exists
}

// Solution 3:
Classroom cls = db.Classrooms.FirstOrDefault(cls => cls.Name == "10A");
if(cls != null) {
    // record exists
}
else {
    // record does not exist
}

// Solution 4: This is the most effective solution
// If you only want to know if such a Record exists:
// This is the most efficient as it generates an IF EXISTS SQL query
return db.Classrooms.Any(cls => cls.Name == "10A"); // true if exists
// Similar expression is:
return db.Classrooms.Where(cls => cls.Name == "10A").Any();

// Solution 5:
// If you want a count of how many such Record exists:
return db.Classrooms.Count(cls => cls.Name == "10A");

// Solution 6:
// If you want an enumeration (IEnumerable<Record>) of all such Record:
return db.Classrooms.Where(cls => cls.Name == "10A");

No comments:

Post a Comment