HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Fetching data from a database

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fetchingfromdatadatabase

Problem

I am fetching data from the database using Entity Framework and Linq queries. I am wondering about the performance of getting data. I just want to check whether or not a well exists in the database. The database table has 15 columns and the number of rows are unknown.

internal static bool WellExists(string name, DatabaseContext context)
{
    var name = context.Wells.Where(w => w.name == name).Select(w => w.name).FirstOrDefault();
    return !string.IsNullOrEmpty(databaseUwi);
}


Here my point of concern is the line in which I am using Linq queries. In this I am using a Where, then Select and then FirstOrDefault. Another solution is using FirstOrDefault only.

var well = context.Wells.FirstOrDefault(w => w.name == name);
return !(well == null);


The first query will get only selected data (Select) which is not required. Which solution's performance is better?

Solution

You can try the .Any function on IQueryable. It is made for checking if there are any records.

Remember that .Any() has an overload that takes an expression, making the solution

internal static bool WellExists(string name, DatabaseContext context)
{
    return context.Wells.Any(x => x.Name == name);
}


I'm going to add a comment about your code as well.
In the second example you have return !(well == null). This obfuscates the meaning of the code a bit, and would be clearer if you write return well != null;

Code Snippets

internal static bool WellExists(string name, DatabaseContext context)
{
    return context.Wells.Any(x => x.Name == name);
}

Context

StackExchange Code Review Q#49314, answer score: 14

Revisions (0)

No revisions yet.