What is the difference between Linq and EF syntax? [duplicate] - c#

This question already has answers here:
Is it Linq or Lambda?
(2 answers)
Closed 5 years ago.
What is difference of
Linq: var data=from a in context.object select a;
EF: var data=context.object().Tolist();

They are both LINQ.
The first is query (expression) syntax
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;
And the other is method syntax
IEnumerable<int> numQuery2 = numbers
.Where(num => num % 2 == 0)
.OrderBy(n => n);
Source: MSDN: Query Syntax and Method Syntax in LINQ (C#)

In your case the difference is that in first case data will be of lazy IEnumerable type and and will be executed on enumerating it.
Second example will enumerate colletion to a list and collection will be in memory after execution of ToList method.
But I assume you are interested in difference between LINQ operators like from, where, select and method Where, Select, etc. There is not difference as operators are compiled to methods.

Difference between both syntax is:
Your 1st query is LINQ to Sql and 2nd one is Entity SQL.
Entity SQL is processed by the Entity Framework Object Services directly
Entity SQL returns ObjectQuery instead of IQueryable

You mean to know the kinds of difference in query syntax while Entity Framework.
Basics of LINQ & Lamda Expressions
LINQ
Linq is the Microsoft's first attempt to integrate queries into language. We know, it is really easy to find data from sql objects simply writing a query while its somewhat hectic when we want to do the same thing in a DataTable or Lists. Generally we will have to loop through every elements to find the exact match, if there is some aggregation we need to aggregate the values etc. Linq provides an easy way to write queries that can run with the in memory objects.
Lamda
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
Hope it Helps.

Related

Expressions in Linq Query

I recently found out that i cannot call any methods from within a linq query. I am trying to write a query that, on the where clause compares two byte arrays. The value on the database is a GUID of type Raw(32) and it is returned as a byte array. This is the record ID for this table. I need to compare it to another byte array. the second byte array could be converted to a string but since i cannot call methods from within linq i was unable to compare.
I tied a custom "Compare" method, i also wrote an extension method. All received an error indicating "LINQ to Entities does not recognize the method"
Here is the code for what i am trying to do. The where clause causes this error:
LINQ to Entities does not recognize the method 'Boolean SequenceEqual[Byte] (System.Collections.Generic.IEnumerable1[System.Byte], System.Collections.Generic.IEnumerable1[System.Byte])' method, and this method cannot be translated into a store expression."
EPSGEntities dbContex = new EPSGEntities();
byte[] byteArray = ParseHex(ViewState["itemID"].ToString());
var q = (from d in dbContex.EPSG_VSOREJECTS
where d.SDSRECID.SequenceEqual(byteArray)
select d).First();
What version of EntityFramework are you using? On EF6 I am able to simply do the following against a SQL 2012 table with a varbinary column:
var q = dbContext.EPSG_VSOREJECTS.FirstOrDefault(e => e.SDSRECID == byteArray);
Is the SDSRECID property on EPSGEntities of type byte[]?
The alternative here would be to go to straight Sql to get your object. Something like:
dbContext.Database.SqlQuery<EPSG_VSOREJECT>("SELECT TOP 1 *" +
"FROM dbo.EPSGEntities" +
"WHERE SDSRECID = #byteString",
new SqlParameter
{
ParameterName = "byteString",
Value = ViewState["itemID"].ToString(),
}).FirstOrDefault();
Linq to Entities in EF is awesome for most queries, but I sometimes drop into sql when I need to do something unsupported, complex, or just fast. Hope this helps!
I'm not entirely sure this works, but I've found calling .AsEnumerable() on the IQueryable object set lets me apply pretty much any code I wish:
var q = dbContex.EPSG_VSOREJECTS.
.AsEnumerable()
.Where(d => d.SDSRECID.SequenceEqual(byteArray));
Doing so seems to prevent EF from trying to translate the Where() clause into SQL syntax, but I have no real idea what the performance hit would/will be.
This is also using method syntax, since I'm not real familiar with query syntax. HTH.
EDIT:
As some others have noted, you have to be careful with how you add any of the iterative methods (AsEnumerable(), ToList(), etc.) since past that point you are no longer building SQL against your data store. Once you start iterating, EF will execute whatever query has been built up to that point, and from then on you are filtering the result set from the LINQ query.
In this case, I don't know that this can be avoided, unless someone can build the same query as a sproc (which EF can execute on your behalf).

Difference between Query Expression and Method Expression in LINQ?

I don't know whether the term of above title is appropriate.
Just like a and b:
var list = Enumerable.Range(0, 100);
var a = from l in list
where l % 2 == 0
select l;
var b = list.Where(l => l % 2 == 0);
When should I use each of them? And any difference?
None, Query expression compiles into Method expression.
Query Syntax and Method Syntax in LINQ (C#)
Because queries return an IEnumerable, you compose them in method
syntax by chaining the method calls together. This is what the
compiler does behind the scenes when you write queries by using query syntax
Also see: LINQ Query Expressions (C# Programming Guide)
At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C#
specification. Any query that can be expressed by using query syntax
can also be expressed by using method syntax. However, in most cases
query syntax is more readable and concise. For more information, see
C# Language Specification and Standard Query Operators Overview.
Apart from that one place where I have found something that can't be done in Query expression is to get the index along with the item. For example you can do following in method syntax:
var result = list.Select((r,i) => new { value = r, index = i});
In query expression an external variable has to be defined to achieve this purpose. Here is a similar discussion with answer from Jon Skeet
No
There is no difference between them.
From Query Syntax and Method Syntax in LINQ
Because queries return an IEnumerable, you compose them in method
syntax by chaining the method calls together. This is what the
compiler does behind the scenes when you write queries by using query
syntax. And because a query variable does not store the results of the
query, you can modify it or use it as the basis for a new query at any
time, even after it has been executed.
Also from LINQ Query Expressions
At compile time, query expressions are converted to Standard Query
Operator method calls.
Query expression is transformed into standard method calls by compiler.
var a = from l in list
where l % 2 == 0
select l;
var b = list.Where(l => l % 2 == 0);
These two are exactly the same in compiled code.
However, not all methods have a keyword associated in query expression syntax.
There's no difference, it's a matter of personal preference. You can even mix the two styles if you want to.
The Linq keywords are translated into the method call syntax by the C# compiler.
The difference, in fact, is no.
In fact, it is one and the same thing, except that the expression for the $a$ the compiler converts to an expression equivalent to expression for $b$.

How to get the product count without using lambda expressions?

I have a table products:
product_id
product_name
prodcut_price
My dbcontext name is abcentity.
I want to get how many number of products (like products count) along with product_id,product_name,product_price.
I have done using lambda expressions using Groupby product_id (this is for Linq to Sql, but I am using linq to entity).
I don't want to use lambda expressions. Is it possible to get the product count without using lambda expressions?
Are you just trying to avoid lambda syntax? You can use the group by clause in LINQ query expression syntax instead of calling .GroupBy().
from p in abcentity.products
group p by p.product_id into g
select new {g.Key, g.Count()}
But I should point out that this still gets compiled as a lambda expression. All you're changing is the syntax you use to represent it.
If you're using Linq to SQL by default, then no. The Expression that is created from making the lambda is what is used to determine the query to create.
If you want a custom expression, you can execute any SQL you define - Scott Gu blogged about how to do this here.
If that is not what you want to do, then perhaps you can explain why you don't want to use lambda expressions?

Custom Method in LINQ to SQL query

Is it possible to use custom method In query for example:
var result = from u in context.MyTable where MyMethod(u) == 10 select u;
As Pranay explains, you cannot have a custom (C#) method as part of the LINQ to SQL query, because LINQ to SQL wouldn't be able to look at the expression tree of the method and so it cannot translate it to SQL.
One option that you have is to write your function in SQL and store it as a SQL function on the SQL Server (possibly, you could also use SQL CLR, but I have not tried that). Then you can add the function to your DataContext type and LINQ to SQL will translate it to calls to the function on SQL server. Something like:
var result = from u in context.MyTable
where context.MyMethod(u) == 10 select u;
The problem, of course, is that you'll need to write the function in SQL (I think SQL CLR could also work - not sure about the performance and other possible complications though)
I also wrote an article (some time ago) that shows how to do this when you write the "method" as an expression tree way (as a value of type Expression<Func<...>>), which is possible, because in this case, the code is compiled as an expression tree. However, there is some postprocessing that has to be done and you can still write just a single expression that can be easily inlined in the LINQ query.
Check this full article : What is and what isn't possible with linq
Following is not possible
// function used in filter
static bool MyFunc(Nwind.Product p)
{
return p.ProductName.StartsWith("B");
}
// query that uses MyFunc
var q =
from p in db.Products
where MyPriceFunc(p.UnitPrice) > 30m
select p
It compiles with no errors, but when you execute it LINQ to SQL throws an exception saying: "Static method System.Boolean MyTest(LINQTest.Nwind.Product) has no supported translation to SQL."
The exception is actually thrown when you try to fetch results from q (for example using the foreach statement), because LINQ to SQL attempts to convert the expression trees to T-SQL only when the results are needed and the query must be executed.
To fix the example you can simply copy the code that checks whether product name starts with "B" to the where clause of the query and it would work fine.
Yes, but if you are using Linq-to-Sql - your method has to have special code to handle to SQL conversion.

How to pass parameters to LINQ to XML query by using lambda expression?

I am new to LINQ to XML in .net(C#, asp.net). I want to know more about Lambda expressions. I am using Lambada expression with the following query.
count = FieldRoot.Element("USER").Element("MM")
.Descendants("MMMS")
.Where(a => a.Attribute("ID").Value == MID)
.SelectMany(b => b.Descendants("ABC")).Count();
Can you please tell me how the Lambda expression work specially in case of parameters (in the above case a & b) ? What is the basic concept of parameters in Lambda expression ? Can we use the names of the variables defined outside of the query instead of a & b ? which elements a & b represent in the above case represent ? Can we pass parameters from outside in the query ? If we can pass parameters from outside query then how it will be done? If you give me any other example instead of the above query to understand the concept of parameter in Lambda expression then it will also help me a lot.
The basic concept is that you're calling Where on a sequence of XElement values - so the lambda expression is executed several times, with a value for a as the "current" XElement. The lambda expression then says whether or not that XElement should be included in the results.
For the SelectMany call, this is effectively flattening a sequence of sequences - from one XElement, you're yielding a sequence of all the ABC descendant elements.
This is really just LINQ to Objects - it's just that LINQ to XML fits in very neatly with LINQ to Objects.

Categories

Resources