LINQ vs context.entity.Where()
Are these two blocks exactly the same? Does one have any advantage over the other?
using (var context = new TRANSITEntities())
{
开发者_运维百科 var result = context.Table1.Where(c => c.UserCode == "123");
}
using (var context = new TRANSITEntities())
{
var result = from c in context.Table1
where c.UserCode == "123"
select c;
}
Exactly the same.
You can verify this yourself by looking at the ToString()
string query1String, query2String;
using (var context = new TRANSITEntities())
{
var result = context.Table1.Where(c => c.UserCode == "123");
query1String = result.Expression.ToString();
}
using (var context = new TRANSITEntities())
{
var result = from c in context.Table1
where c.UserCode == "123"
select c;
var query2String = result.Expression.ToString();
}
Assert.AreEqual(query1String, query2String);
It should also be noted that result
is NOT actually a result. It's a non-executed/enumerated IQueryable
. Meaning it's like a SQL statement that hasn't been run yet (sort of). If you were to do
var t1 = result.ToArray()
var t2 = result.ToArray()
then the query would actually be executed twice. t1
and t2
are the REAL results (an in memory array)...not result
. In other words, result
should really be named query
And further, the example you have above will never work...because if you call ToArray
on the result outside of the using
block, it will fail...because you can't run the query once the context is disposed:
using (var context = new TRANSITEntities())
{
var result = context.Table1.Where(c => c.UserCode == "123");
}
// throws exception:
var array = result.ToArray();
They're exactly the same. The compiler converts the query syntax to the lambda expression version before it resolves any methods.
Well the first selects from context.Table1
, the second selects from context.LINTE
. So they select from totally different collections.
Also the first selects on a UserCode column and the second on a CodeUsager column..
Apart from that (is the first just a translation of the second and you forgot to translate the second) the code is the same. The C# compiler will just translate the second query into the first one and they will behave identically.
If you are trying to select from different tables then it is different.
But if the tables are same then it is just the representation different.
There is no difference it is just the preference which way you like to code.
All the linq queries are converted to Lambda before creating the sql representation.
From Julia Lermans' book Programming Entity Framework:
The MSDN documentation says, “In general, we recommend query syntax because it is usually simpler and more readable; however, there is no semantic difference between method syntax and query syntax.”* Therefore, using one over the other is a matter of style and personal choice.
精彩评论