Join Nhibernate - linq

I have list with ids
List<int> listOfIds;
And I have a query with cars objects.
I would like to do something like this:
query = from e in query
join b listOfIdson e.b.Id equals b
select e;
but then I get error:
Specified method is not supported.
I know that its possible to do that by Join method which is avaiable on my query, but I have no idea how to do this. I can run following Join methods on my query:
query.Join()
query.JoinGroup()
Thats all
Thanks for help

Could you try with QueryOver ?
var results = session.QueryOver<Car>().AndRestrictionOn(x=> x.id).IsIn(listOfIds)

Related

Dynamic Linq core

Hi I am using a Jqwidgets Grid to display my data. It has a build in possibility to use filters but if you filter your records on the server side you have to build your own query. As I am working with Linq I thought to use the Dynamic Linq Library for Asp net core. Problem is there are not many examples or explanations how to do this. But I am busy for days now and not getting very far.The way I am setup; I have a normal Linq query:
var Mut = from M in _DB.Mutations
join S in _DB.Shifts on M.ShiftId equals S.ShiftId
join U in _DB.RoosterUsers on M.UserId equals U.RoosterUserId
join D in deps on M.UserId equals D.UserId
join DD in _DB.Departements on D.DepartementID equals DD.DepartementId
select new MutationModel
{
MutId=M.MutationId,
Naam=U.FirstName + " " + U.LastName,
UserId=M.UserId,
Departement= DD.DepartementName,
MutationType = S.publicName,
MutationGroup = S.ShiftType.ToString(),
DateTot =M.DateTill,
TijdVan=M.DateStartOn,
TijdTot=M.DateTill,
Status=CreateStatus(M.Tentative, M.ApprovedOn, M.Processed, M.CancelRefId, M.Deleted)
};
This query is running OK and gives me all the data I need for the Grid.
Then for the filter I would like to add a dynamic Linq Query using the System.Linq.Dynamic.Core library
But this is as far as I get things working until now:
var outQuery = Mut.Where("Status = #0 and UserId = #1", "Nieuw", "KLM22940").Select("Status");
My questions now :
1. In the where clause If I make the fieldname variable I get an error. how to do this??
2. In the Select Clause, how to add multiple Columns? (actually I just like to output all columns.)
Best would be to see an example. has somebody used Dynamic Linq to build a dynamic linq query for the JQWidgets Grid?
Thank you very much.
In what way you are trying to use fieldname variable in where clause ?
If you want to output all columns you can use ToList()
like
var outQuery = Mut.Where("Status = #0 and UserId = #1", "Nieuw", "KLM22940").ToList();
If you want to get some specific columns you can use Select clause like this
var outQuery = Mut.Where("Status = #0 and UserId = #1", "Nieuw", "KLM22940").Select("new(Status,UserId )");
This Select clause creates data class which contains Status and UserId properties and returns a sequence of instances of that data class.

Linq Left Outer Join Two Tables on Two Fields

How do I left outer join two tables on two fields in linq?
I have a sql:
select a.*, b.* from courselist as a
left outer join Summary as b
on a.subject = b.Subject and a.catalog =
b.Catalogno
where a.degree_id = 1
order by a.sequenceNo
Below is my linq query, but there is error underline "join", failed in the call to "Groupjoin". I don't know how to correct that.
var searchResults = (from a in db.courselist
join b in db.Summary on
new { a.subject,a.catalog } equals
new { b.Subject, b.Catalogno } into ab
where a.degree_id == 1
orderby a.degree_sequenceNo
from b in ab.DefaultIfEmpty()
select new
{
Courselist = a,
Summary = b
}
).ToList();
Thanks.
I've checked your code again,
I found it's fault
you just need to specify join parameters name like this:
new { suject = a.subject, catalog = a.catalog } equals
new { suject = b.subject, catalog = b.Catalogno } into ab
It seems you are missing the reference, the query doesn't have an error
try to use this:
using System.Linq;
The main issue when people start using LINQ is that they keep thinking in the SQL way, they design the SQL query first and then translate it to LINQ. You need to learn how to think in the LINQ way and your LINQ query will become neater and simpler. For instance, in your LINQ you don't need joins. You should use Associations/Navigation Properties instead. Check this post for more details.
There should be a relationship between courselist and Summary, in which case, you can access Summary through courselist like this:
var searchResults = (from a in db.courselist
where a.degree_id == 1
orderby a.degree_sequenceNo
select new {
Courselist = a,
Summary = a.Summary
}).ToList();
If there is no relationship between the two, then you should reconsider your design.

Performing two Left Outer Joins in a Single LINQ to CRM query

I'm attempting to perform two left outer joins in my CRM online 2015 Update 1 instance, but I am getting an error. This is what I have currently:
var query_join8 = from a in crmContext.AccountSet
join c in crmContext.ContactSet
on a.PrimaryContactId.Id equals c.ContactId
into gr
from c_joined in gr.DefaultIfEmpty()
join c in crmContext.ContactSet
on a.Name equals c.FullName
into gr2
from c2_joined in gr2.DefaultIfEmpty()
select new
{
contact_name = c_joined.FullName,
account_name = a.Name,
other_name = c2_joined.FullName
};
When I attempt to execute it, I get this error:
An exception of type 'System.NotSupportedException' occurred in
Microsoft.Xrm.Sdk.dll but was not handled in user code
Additional information: The method 'GroupJoin' cannot follow the
method 'SelectMany' or is not supported. Try writing the query in
terms of supported methods or call the 'AsEnumerable' or 'ToList'
method before calling unsupported methods.
If I comment out the second Join, it works fine:
var query_join8 = from a in crmContext.AccountSet
join c in crmContext.ContactSet
on a.PrimaryContactId.Id equals c.ContactId
into gr
from c_joined in gr.DefaultIfEmpty()
//join c in crmContext.ContactSet
//on a.Name equals c.FullName
//into gr2
//from c2_joined in gr2.DefaultIfEmpty()
select new
{
contact_name = c_joined.FullName,
account_name = a.Name,
//other_name = c2_joined.FullName
};
Microsoft Documentation:
Defining how to perform a Left Join: http://msdn.microsoft.com/en-us/library/gg509017.aspx#LeftJoin
Blog Describing that it is supported: http://blogs.msdn.com/b/crminthefield/archive/2013/01/14/crm-2011-sdk-query-limitations-by-api.aspx
The documentation on CRM 2015 still states outer joins are not supported. (MSDN: Use LINQ to construct a query) I know there is also an example on MSDN showing a left join (Sample: Complex LINQ queries), but I doubt if under the hood this is actually transformed into a single QueryExpression. So, I guess you are hitting the limits of the capabilities of Ling for CRM.

complex orderby that links to another table

I have the following query to start with:
var query = from p in db.Products
from pc in p.NpProductCategories
where pc.CategoryId == categoryId
select p;
I'm applying some more filtering on it and in the end I want to sort the results:
if (orderBy == ProductSortingEnum.Name)
query = query.OrderBy(x => x.Name);
else
query = query.OrderBy(............);
My big problem (coming from not knowing linq too good) is the ELSE here. How can I sort results by a column that is not in the current result set? I would like to somehow link to another linq query in the orderby. The sorting I'm trying to achive is to link to NpProductVariants query using the ProductId to match between NpProductVariant and Products
and sort by the Price of the NpProductVariant
Assuming you have the relationship set up in the dbml...
For one to one (and many to one):
query = query.OrderBy(p => p.NpProductVariant.Price);
For one to many:
query = query.OrderBy(p => p.NpProductVariants.Select(v => v.Price).Max());
Also:
var query =
from p in db.Products
where p.NpProductCategories.Any(pc => pc.CategoryId == categoryId)
select p;
I think you can hook your Join to your query as long as it is returning the same thing. So maybe something like (I'm not 100 % sure since I haven't tried it):
query = from i1 in query
join i2 in query2 on i1.PropertyToJoin equals i2.PropertyToJoin
orderby i1.OrderProp1, i2.OrderProp2
select i1;
But I think it might be a good idea to check the generated sql so it is still effective.

FirstOrDefault behavior directly in LINQ statement

Seems like I may have missed something simple in the syntax, but I'd like to get the results of FirstOrDefault from a linq statement directly without having to store the IEnumerable in a temporary variable first. Something like this:
var bestCar = from c in cars
orderby c.Price
select first c
I know the first keyword doesn't actually exist but illustrates what I'd like to do. I also know I can wrap the from...select statement in parenthesis and call FirstOrDefault directly but I think the above syntax is cleaner and easier to read.
Enumerable.FirstOrDefault is one of the extension methods in the Enumerable class which does not have a corresponding LINQ syntax element. The only way to bind to this method is via method call syntax.
You can avoid the temporary by doing the follownig
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
There isn't a way to do that. LINQ is used for defining a query. Doing that doesn't actually cause an evaluation, whereas executing FirstOrDefault (or enumerating over it) executes the query.
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault()
OR
var bestCar = cars.OrderBy(c => c.Price).FirstOrDefault()
var bestCar = (from c in cars
orderby c.Price
select c).FirstOrDefault();
Sorry I didn't read your question entirely, it seems that this may be exactly what you don't want to do.
In VB you can use 'Aggregate':
Dim BestCar = Aggregate c In cars
Order By c.Price
Into FirstOrDefault

Resources