Dynamic linq/lambda expression from query - linq

I have data query and want to create dynamic linq/lambda expression which i can run on entity collection. Not sure how to do this using Expression builder. Please provide some examples if possible.
For e.g I have query
Select person.name,person.surname from person where person.name= 'Joe'
and i have entity collection of all persons. But dont want to fire a query instead want to convert this query in to lambda and run on persons collection. This to avoid server calls.
linq/lambda expression like
from person in person where person.id ='Joe' select person.name;

It's better to use method syntax rather than query syntax
for example instead of from person in people where person.Name == "Test"
use People.Where(person => person.Name == "Test");
then you can add reference to Mono.CSharp.DLL and then use Evaluator class to compile and run C# codes on the fly easily, without loosing performance too much.
Then compile and run your LINQ queries by C# strings and invoke that string with Evaluator.
You can see this method in JavaScript codes too, with eval function.
Let me know if other information are needed
Good luck

LINQ
var xxx = from p in person
where p.Name equals "Joe"
select p;
Lamda
var lambda = Person.Where(m=> m.Name == "Joe");
For tutorials
MSDN 101 LINQ
MSDN
Lambda

Related

What should you use for joining in LINQ, Query syntax or method syntax?

I would like to know in terms of performance is there any difference between using a query syntax or method syntax (Lambda expressions) for joining two entities?
I already know that in general there are no difference in terms of result, between query syntax and method syntax. However, for joining which of these are better to use performance wise?
Here is the sample code:
var queryResult = (from p in People
join i in Incomes
on p.PersonId equals i.PersonId
select new { p.PersonId, p.Name, p.Age, i.Amount }
).ToList();
var lambdaResult = People.Join(Incomes,
p => p.PersonId,
i => i.PersonId,
(p, i) => new { p.PersonId, p.Name, p.Age, i.Amount }).ToList();
I have already went through these websites but nothing has been mentioned for join
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq
LINQ - Query syntax vs method chains & lambda
There is no difference. Your first version (query language) is translated lexically into the second one (method syntax) before "real" compilation. The query language is only syntactic sugar and transformed into method calls. These calls are then compiled (if possible - the translation itself does not care about the correctness of the result, e.g. if People.Join even is valid C# and there is such a Join method in whatever People might be).
There maybe a difference in that this translation uses an explicit Select call instead of the resultSelector parameter of the Join method, but even that does not measurably impact performance.
This article by Jon Skeet helped me understand the transformation from query language to method syntax.
To answer the question "What should you use": this is really up to you. Consider:
what is more readable/understandable to you (and your co-workers!)
complex queries often are more readable in query syntax, the SQL-like style can be easier to read than a long chain of method calls
Note that every query syntax expression can be expressed as method calls, but not all method calls can be expressed in query syntax
mixing both syntaxes in a single query is often more confusing than sticking to one of them

Linq to NHibernate and Dynamic LINQ - query caching not working

I have problem with the NHibernate's second level cache. When I use query:
var items1 = Session.Query<Row>()
.Cacheable();
.Fetch(x => x.Field)
.OrderBy(x => x.Field.Value)
.ToList();
Everything is fine - the query is cached. But when I want to use Dynamic Linq (a link):
var items2 = Session.Query<Row>()
.Cacheable();
.Fetch(x => x.Field)
.OrderBy("Field.Value")
.ToList();
The query is not cached. Interesting thing is that, when I delete code line:
.Fetch(x => x.Field)
caching works again. So the problem is with using Fetch and dynamic linq OrderBy methods together.
EDIT:
When I try do debug NH code (QueryKey class), debugger tells me that these two queries do not have the same ResultTransformer (and deeper: a listTransformation private instance).
Any ideas?
Chris
Ok, I know what is the reason.
Dynamic Linq doesn't use Parameter Names in Linq Expressions. E.g. if I want to sort using lambda statemant, I write:
query.OrderBy(item => item.Name)
Above we see an item lambda parameter name.
When I use Dynamic linq:
query.OrderBy("Name")
in the result Queryable the lambda parameter in OrderBy mehod has no name (like item written above). We can illustrate the result like this:
query.OrderBy( => .Name)
And now, when NHibernate is decoding that Queryable expression and finds there an expression parameter that has no name, NH gives it a random name using GUID class. So every ordering using dynamic linq produces a Queryable Expression that has inconstant lambda parameter. This is the reason why NHibernate thinks that: query.OrderBy("Name") and query.OrderBy("Name") are not the same - they have another lamda parameters generated every time from scratch.
SOLUTION
If you want to fix it, you have to modify Dynamic Linq library.
In method ExpressionParser.ProcessParameters change line:
if (parameters.Length == 1 && String.IsNullOrEmpty(parameters[0].Name))
to:
if (parameters.Length == 1 && (parameters[0].Name == "it" || String.IsNullOrEmpty(parameters[0].Name)))
In method DynamicQueryable.OrderBy change line:
Expression.Parameter(source.ElementType, "")
to:
Expression.Parameter(source.ElementType, "it")
Now, query.OrderBy("Name") will produce query.OrderBy(it => it.Name).
Cheers!

Extension Method To Take A Dynamically Built Search Expression?

I think we are basically looking for a extension method that could take in an IQueryable and return an IQueryable based on an entire query statement and not just the where statement.
Example of what we would like for a Search Method:
IRepository<Person> repository = new Repository<Person>();
var results = repository.GetQuery().Include("Names").Search([dynamic linq here]);
We currently have where we build a dynamic linq statement inside the where method
IRepository<Person> repository = new Repository<Person>();
var results = repository.GetQuery().Include("Names").Where([dynamic linq here]);
The problem with that approach is that we want to do include SelectMany and Select on the actual dynamic linq query. You cannot use the SelectMany inside a Where method unless you are actually going into sub properties of sub properties. We would like to do something like the following dynamic linq statement.
SelectMany("Names").Where("LastName.Contains(#0)", "Smith").Select("Person")
We solved this issue without having to use a extension method. We were able to use a similar query that works inside a Where method.
So instead of...
SelectMany("Names").Where("LastName.Contains(#0)", "Smith").Select("Person")
We were able to get the same result with the following query that can be inside a Where method.
Where.("Names.Select(LastName).Contains(#0)", "Smith)
Then when just had to add a Contains Aggregate to the Dynamic Linq library.
http://blog.walteralmeida.com/2010/05/advanced-linq-dynamic-linq-library-add-support-for-contains-extension-.html
The SelectMany had sent us off on a wild goose chase!
Checkout this nuget package: NinjaNye.SearchExensions
It enables you to do something like the following:
var repository = new Repository<Person>();
var results = repository.GetQuery().Search(p => p.LastName, "Smith");
Connected to sql this will produce something smilar to the following:
SELECT [Extent1].[Id] AS [Id],
... [other properties],
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE ([Extent1].[LastName] LIKE N'%Smith%')
The query is built using expression trees so the result is clean.
Check out the source code here:
https://github.com/ninjanye/SearchExtensions/

Linq Containsfunction problem

I use Ria Service domainservice for data query.
In My database, there is a table People with firstname, lastname. Then I use EF/RIA services for data processing.
Then I create a Filter ViewModel to capture user inputs, based it the input, I construct a linq Query to access data.
At server side, the default DomainService query for person is:
public IQueryable<Person> GetPerson()
{
return this.Context.Person;
}
At client side, the linq Query for filter is something like(I use Contains function here):
if (!String.IsNullOrEmpty(this.LastName))
q = q.Where(p => (p.LastName.Contains(this.LastName)));
The generated linq query is something like(when debugging,I got it):
MyData.Person[].Where(p => (p.LastName.Contains(value(MyViewModel.PersonFilterVM).LastName) || p.Person.LegalLastName.Contains(value(MyViewModel.PersonFilterVM).LastName)))
When I run the app, I put "Smith" for last name for search, but the result is totally irrelevant with "Smith"!
How to fix it?
I'm guessing here as to what your error is so this might not work for you.
In your 2nd code snippet you do the following.
q = q.Where(p => (p.LastName.Contains(this.LastName)));
This is where I think your error is. Linq does not evaluate the where clause until you iterate over it. Try changing the line to the following.
qWithData = q.Where(p => (p.LastName.Contains(this.LastName))).ToList();
The .ToList() call will load the query with data.
When you check in the debugger, does value(MyViewModel.PersonFilterVM).LastName evaluate to Smith at the time the query is resolved?
Recall that queries are not resolved until they are enumerated.

Return Datatype of Linq Query Result

I think I'm missing something really basic.
var signatures=from person in db.People
where person.Active==true
select new{person.ID, person.Lname, person.Fname};
This linq query works, but I have no idea how to return the results as a public method of a class.
Examples always seem to show returning the whole entity (like IQueryable<People>), but in this case I only want to return a subset as SomeKindOfList<int, string, string>. Since I can't use var, what do I use?
Thanks!
You can get concrete types out of a linq query, but in your case you are constructing anonymous types by using
select new{person.ID, person.Lname, person.Fname};
If instead, you coded a class called "Person", and did this:
select new Person(peson.ID, person.Lname, person.Fname);
Your linq result (signatures) can be of type IEnumerable<Person>, and that is a type that you can return from your function.
Example:
IEnumerable<Person> signatures = from person in db.People
where person.Active==true
select new Person(person.ID, person.Lname, person.Fname);

Resources