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?
-
3\$\begingroup\$ I suggest perhaps profiling the query and seeing what the underlying SQL is. LinqPad is quite good for this, or I believe you should be able to see the SQL in debugger. In spite of that I think you will find all your examples generate the same underlying SQL \$\endgroup\$dreza– dreza2014年05月09日 09:51:48 +00:00Commented May 9, 2014 at 9:51
-
7\$\begingroup\$ If you want to know the performance of something measure it and then you'll know. This question is like saying "I have a horse, does anyone know how fast it runs?" How should we know? If you have two horses and want to know which is faster, race them, don't ask strangers on the internet which one will win the race. \$\endgroup\$Eric Lippert– Eric Lippert2014年05月09日 13:46:57 +00:00Commented May 9, 2014 at 13:46
1 Answer 1
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;