Predicate to SQL through LINQ [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 17 days ago.
Improve this question
Is there a way to translate predicate(Func<T,bool>) using LINQ to SQL query or something similar to this?
Found nothing on internet or MS guides.

ORMs (like Entity Framework, linq2db, and others) in C# usually use expression trees and IQueryable to be able to translate the code into actual SQL queries, so they need Expression<Func<T, bool>>, not just Func<T, bool>. If you are creating the predicate via lambda then compiler can also translate it to expression tree, i.e.:
Func<MyClass, bool> predicate = mc => mc.IntProp == 1;
Exppression<Func<MyClass, bool>> predicate = mc => mc.IntProp == 1;
Will work both well. So in some cases you can just change your method parameter and that's it.
Read more:
Expression Trees
What is the difference between IQueryable and IEnumerable?
LINQKit - interesting library which does some magic around LINQ

Short awnser : no
Long awnser : yes... but actually no
There is no way to accuratly translate a programming language into another without the risk of the function and meaning being altered
(you could use this but even that is no longer mantained)
I would recommend you learning LinQ in order to safely translate it without mistakes.
You could also post you query so anyone like me or other more fitted members to help you out in the translation.

Related

Sql Timeout when converting IEnumerable<T> to List<T> in C# Entityframework [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
There are around 2800 records fetched from database in 2 sec with following code
public IEnumerable<T> ExecWithStoreProcedure(string query, params object[] parameters)
{
return db.Database.SqlQuery<T>(query, parameters);
}
but when converting to list, Sql Timeout comes. I am using EntityFramework with SQL database. How to achieve Performance in less than 15 sec.
Entity Framework uses lazy evaluation, meaning that simply calling SqlQuery doesn't actually perform the query, it simply builds it. Only when the IQueryable/IEnumerable is materialized, that's when the actual query is performed. So when you call ToList(), that's the point where your query is executed.
As to why it's slow - that's up to the query itself. No way to tell from the code here.
try using this in your method befor fire a query command
this.context.CommandTimeout = 180;

LINQ: Why use ...Take(1).SingleOrDefault()? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm currently examining some code I'm going to maintain.
I see a few occasions of
.Take(1).SingleOrDefault()
Why would you use that instead of simply
.First() or .FirstOrDefault()
(I'm not sure whether .Take(1) would throw an exeption if the result set is empty, which imho would make the difference between the two .First... Methods?)
It is impossible for us to know for sure the inner implementation of whatever LINQ provider you may be using. They all vary in how they do it. Some may be more performant in cases like this whereas others may be less performant. You should get the same result either way.
It is not possible for us to read someones mind to determine why they would have done it this way in this case.
With that said, if you want to dig in deeper and it is a SQL provider, you can see what SQL it generates and compare the two cases.
The main objection is that .Take(1).SingleOrDefault() defeats the purpose of SingleOrDefault, which is to throw an exception when the LINQ query returns more than one element.
To illustrate this, when running LINQ against a Sql Server backend Single(OrDefault) will translate into SELECT TOP (2) ... in order to determine whether there actually is one record. Preceding this by Take(1) will never return more than one record, so the "multiple result" exception will never occur although the code seems to require it. This code looks like a (premature) optimization by someone who's worried about returning two objects instead of one.
So the answer to your question "Why would you use that?" is: there's absolutely no reason to do it this way. There are only reasons not to do it.

Understanding AsEnumerable in Linq to Objects [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Written on msdn:
Returns the input typed as IEnumerable<T>.
I do not understand.
Help me to understand this method.
There are three implementations of AsEnumerable.
DataTableExtensions.AsEnumerable
Extends a DataTable to give it an IEnumerable interface so you can use Linq against the DataTable.
Enumerable.AsEnumerable<TSource> and ParallelEnumerable.AsEnumerable<TSource>
The AsEnumerable<TSource>(IEnumerable<TSource>) method has no effect
other than to change the compile-time type of source from a type that
implements IEnumerable<T> to IEnumerable<T> itself.
AsEnumerable<TSource>(IEnumerable<TSource>) can be used to choose
between query implementations when a sequence implements
IEnumerable<T> but also has a different set of public query methods
available. For example, given a generic class Table that implements
IEnumerable<T> and has its own methods such as Where, Select, and
SelectMany, a call to Where would invoke the public Where method of
Table. A Table type that represents a database table could have a
Where method that takes the predicate argument as an expression tree
and converts the tree to SQL for remote execution. If remote execution
is not desired, for example because the predicate invokes a local
method, the AsEnumerable<TSource> method can be used to hide the
custom methods and instead make the standard query operators
available.
In other words.
If I have an
IQueryable<X> sequence = ...;
from a Linq Provider, like Entity Framework, and I do,
sequence.Where(x => SomeUnusualPredicate(x));
that query will be composed on and run on the server. This will fail at runtime because Entity Framework doesn't know how to convert SomeUnusualPredicate into SQL.
If I want that to run the statement with Linq to Objects instead, I do,
sequence.AsEnumerable().Where(x => SomeUnusualPredicate(x));
now the server will return all the data and the Enumerable.Where from Linq to Objects will be used instead of the Query Provider's implementation.
It won't matter that Entity Framework doesn't know how to interpret SomeUnusualPredicate, my function will be used directly. (However, this may be an inefficient approach since all rows will be returned from the server.)

What is the difference between Queryable.OrderBy and Enumerable.OrderBy? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Suppose I have a LINQ to SQL (or EntityFramework) data context (object context). I want to query some data from it and sort the result set. The query would look like:
using(var dc = new TestDataContext) // = new TestEntities)
{
var query = dc.MyEntities.Where(e => /*my where clause*/)
.OrderBy(/*my sorting field*/)
.ThenBy(/*another sorting field*/);
foreach(var entity in query)
{
//...
}
}
Depending on the type of an argument different OrderBy and ThenBy methods may be used.
Queryable.OrderBy Method with Expression<Func<TSource, TKey>>
Enumerable.OrderBy Method with Func<TSource, TKey>
In DataContext.Log one can see that Queryable.OrderBy compiles the given expression into the SQL statement executed over the database, while when using Enumerable.OrderBy LINQ actually does the sorting over the objects in the programm's memory, i.e. the query over the database is executed without sorting...
What are other possible peculiarities, I may come across?
This question arised after this: SO How to make expression treat value type as a reference type?
In DataContext.Log one can see that Queryable.OrderBy compiles the
given expression into the SQL statement executed over the database,
while when using Enumerable.OrderBy LINQ actually does the sorting
over the objects in the programm's memory,
That's the only difference. And because compiler can translate your lambda Func<T> into Expression<Func<T>> the Queryable.OrderBy will be used by default.
When a lambda expression is assigned to a variable, field, or parameter whose type is Expression<TDelegate>, the compiler emits instructions to build an expression tree.
from Expression<TDelegate> Class
If you really need to perform LINQ to Objects Enumerable.OrderBy call AsEnumerable() before OrderBy call.
The difference here is that persistence frameworks such as NHibernate and Entity Framework have their own LINQ providers that traverse expression trees and build SQL queries. This is thanks to deferred execution. Nothing actually happens with an IQueryable until something forces the provider to evaluate it.
On the other hand.. LINQ can do in-memory queries AFTER the above has taken place. Maybe this will make more sense:
var result = db.Entities.Table
.Where(x => x.Id == 1) // SQL WHERE clause
.OrderBy(x => x.Id) // SQL ORDER BY clause
.ToList() // Query the database and store result
.Sum(x => x.SomethingElse) // Sum the field in memory
.ToList(); // convert back to a list.
As you can see.. halfway through that chain the provider hits the database with a generated query. The ToList() call forces the provider to query the database for results. After that, it's all in-memory.

c# convert string expression to a boolean expression [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Is it possible to convert a string expression into a boolean condition?
For example, I get the following string:
var b = "32 < 45 && 32 > 20"
I would like to create a bool expression out of this and invoke it. The string representation is also flexible (to make it more fun), so it allows ||, &&, ().
Have a look at Flee (Fast Lightweight Expression Evaluator) on CodePlex.
I would use Irony, the .NET language kit. You could construct a simple grammar with Irony and then parse the string into executable command. There's a decent example of an arthmetic grammar in this tutorial and in the Expression Grammar Sample, its a pretty common request ;)
I definitely suggest using a proper compiler as opposed to Regex or a roll your own approach - it will be much more extensible if you ever want to add more rules.
If it follows all C# expression rules then compile it as dynamic code as per http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm
If you're dealing with relatively simple mathematical expressions then a straightforward implementation of the shunting-yard algorithm should do the trick.
Take a look at my library, Proviant. It's a .NET Standard library using the Shunting Yard algorithm to evaluate boolean expressions. You could also implement your own grammar.
I think creating an interpreter for this string would not take too long time.
http://www.industriallogic.com/xp/refactoring/implicitLanguageWithInterpreter.html
here you can find information about design that can be used to create it.
You could take a look at JINT (Javascript Interpreter for .NET) http://jint.codeplex.com/

Categories