LINQ query does not work without .ToList() - linq

Consider following LINQ-to-NHibernate queries:
var q1 = from se in query.ToList<SomeEntity>()
where
prop1 == "abc"
select se;
var q2 = from se in q1
where
m1(se.prop2) == "def"
select se;
q2 will not work with error: "The method m1 is not implemented". But when replace q2 with following query, everything goes ok:
var q2 = from se in q1.ToList<SomeEntity>()
where
m1(se.prop2) == "def"
select se;
Why this happens? How can I get first query to work too? Is this something that happens for LINQ-to-NHibernate only or happens in all LINQ queries?

Because there is no way for the LINQ provider to translate the method m1 to a compatible SQL statement.
By calling ToList<SomeEntity>(), you are reading the entire thing into memory and then using LINQ to Objects to filter (and since the query doesn't get translated to SQL in that case, there is no problem running the query).
Unfortunately there is no easy way for you to get the first query to work. If you really need to use m1 to filter results, you'll have to read things into memory first.
This is not just a LINQ to nHibernate limitation either. This will happen in any situation where a LINQ provider uses Expression Trees to convert your code into another language (in this case it is trying to convert your C# code into SQL statements which is the same thing that LINQ to SQL and Entity Framework do).

Presumably the method m1 does not have a translation to SQL (at least, the NHibernate LINQ provider can't figure out how to). When you don't have the ToList, NHibernate is trying to figure out how to convert m1 to SQL. When you do the ToList, NHibernate isn't playing a role anymore and its LINQ-to-Objects that can handle the query. This is specific to ORMs that enable LINQ; LINQ-to-SQL and EF will suffer similar fates.

I would say that your original q2 query is being translated into an expression tree and then when NHibernate tries to parse it, it finds that the method is not a part of its implementation. Converting the query to a collection first with ToList() uses the LINQ functionality of the List which can support the m1 method.

I don't know NHibernate, but would this work ?
var q2 = q1.where (x => m1(x.prop2) == "def");

Related

LINQ Lambda Order in writing the query

I have the following query:
var query = db.Prog
.Where (a => a.Prog != "00000" && a.fn != "Koll")
.Select(a => new {a.Prog, a.MEfn})
.OrderByDescending(a => a.MEfn)
The query works fine but wondering if there are general rules on the order in which you write a Lambda linq query. Meaning, .Where comes before .Select, etc.
Can somebody enlighten me on the order in which LINQ needs to be written or best practices.
There isn't a best practice on the order in which you write a LINQ query, it will depend on if you want to do your filtering first, or your projection. For example in your case, you are projecting to an anonymous type which doesn't include the 'fn' property which your filter uses, so it wouldn't be available to use in a where clause if your select was first.
A better practice would be to give your properties less cryptic names. Also, 'fn' doesn't follow the PascalCase for property names, and if it's a field then it probably shouldn't be public.
Yours can be a good order.
Let's distinguish the case where db points to an SQL DB with a very good LINQ provider and the case db is an in-memory object. I guess it's the first.
In case you are using a LINQ to SQL provider, the statements are evaluated only when you materialize the query into an object, so the SQL optimizer (inside the DB) will take care of ordering of statements.
The vice versa occurs when your statements are run against in-memory collections or to materialized collections coming from LINQ to SQL. In that case they are executed sequentially, so you want to execute first those statements that reduce the number of results in the collection. Where is the best candidate!!!
The order that they should be in are completely dependent on the context of what you are doing. So if your OrderBy is simply formatting the data to be friendly to view, put it at the end after you have trimmed your collection, if your looking for the First value of a sorted collection then maybe you would need it before the collection is iterated to get the first.

Linq to ... and Lambda Expressions

I have a big question that has been puzzling me for a long time and that I can't seem to get a straight answer for anywhere and I am sure that if someone can answer this with authority and with good examples that it will help not only me but thousands of developers to come. All I want to know is what are the characteristics of the following concepts and what are the differences between them
Linq
Linq to SQL
Linq to Entities
Linq to Objects
Lambda expressions
Also, in particular, can someone tell us where constructs such as these fall into the above categories
Construct 1
var result = from n in nums
where n < 5
orderby n
select n;
Construct 2
Entities.Person.Where(p => p.FirstName == "John").First();
Your learned clarifications are eagerly awaited.
I'm sure there are some over-simplifications here, but for what it's worth:
Linq is an API designed for dealing with data sets. IQueryable, for instance, comes from the System.Linq namespace. Linq to ... are different implementations that parse the same Linq instructions to perform different operations based on how your data is stored. So Linq to SQL will parse your .Where instruction to produce a sql query with a WHERE clause, while Linq to Objects would take that same instruction and produce a foreach.
A lambda expression is pretty much a shorthand for an anonymous delegate. You identify a lambda by the => operator. Your argument list is at the left hand of the => and the expression that can access those arguments and optionally return a result is at the right hand.
Your two code examples are different syntaxes in which Linq queries can be written. They are called Query syntax and Method syntax, respectively.

Dynamic linq: passing entire query as string

Looking at Dynamic Linq, it's possible to use strings to define the key parts of the query. My question is, is it possible to pass the entire query in as a string?
ie: var foo = "from..."
LINQ stands for "Language INtegrated Queries" - it's compiled with the rest of the code, not parsed on the run. You can use Microsoft.CSharp.CSharpCodeProvider to compile your query on the run - but you will have to know in advance what local objects you want to send to the query.
That's not possible in dynamic LINQ -- dynamic LINQ only replaces specific pieces of the query. You can use ExecuteQuery on the data context in LINQ to SQL or SqlQuery on a DbSet<T>, though, to execute specific SQL commands.

Linq, what is difference in returning data in var, list, IEnumerable and IQueryable?

I am new to Linq please guide me on some basic things.
In read some articles on Linq. Some authers fill data in var from Linq query, some fills list of custom type objects and some fills data in IEnumerable and some do it in IQuryable. I could not get what is difference in these 4 and which one should be used in which situation.
I want to use Linq to SQL. What should I use?
Well, you can never declare that a method returns var - it's only valid for local variables. It basically means "compiler, please infer the static type of this variable based on the expression on the right hand side of the assignment operator".
Usually a LINQ to Objects query will return an IEnumerable<T> if it's returning a sequence of some kind, or just a single instance for things like First().
A LINQ to SQL or EF query will use IQueryable<T> if they want further query options to be able to build on the existing query, with the added bits being analyzed as part of the SQL building process. Alternatively, using IEnumerable<T> means any further processing is carried out client-side.
Rather than focusing on what return type to use, I suggest you read up on the core concepts of LINQ (and the language enhancements themselves, like var) - that way you'll get a better feel for why these options exist, and what their different use cases are.

Linq to Nibernate design

I thought that the purpose of using Linq2Nibernate was to return IQueryable and build up an expression tree. I am not sure if this is correct or not.
Why would anyone use Linq2Nibernate if they are not going to return IQueryable?
What else would it be used for?
I would love some more input on this topic
Linq For Nhibernate
I'm planning to use NHibernate.Linq to replace my HQL and criteria API queries with LINQ expressions. In other words, I'll generate the query in code (as a LINQ expression) and then pass it to NHibernate.Linq and NHib to convert it into a database query.
FYI there is an alpha version available.
I have planed to start using Linq2Nibernate but haven't got round to i yet.
My reason for wanting to user Linq2Nibernate is the nice syntax when constructing criterions and later querying them out.
Here is a nice simple example.
http://ayende.com/Blog/archive/2007/03/16/Linq-for-NHibernate.aspx
I am using Linq2Nhibernate with my repository pattern that returns IQueryable objects.
As you know, IQueryable is only a query definition - doesn't touch database yet.
Then local requirements are added to the query and finally the object or list is materialized.
Seems to work excellent and prevents unnecessary db queries for partial data at higher abstract layers.
What's Linq2NHibernate? As there are several projects which tried to implement a linq provider for nhibernate but all stopped before reaching completion.
Any linq provider needs to return IQueryable, or better an IEnumerable as that's how linq works. It's convenient to return an IQueryable as you then can re-use existing code to pad additional operators to an already created query (as ctx.Employee which might return IQueryable is already a query)

Resources