How to create a temporary column + when + order by with Criteria Builder - sql-order-by

here is the sql statement I am trying to translate in jpa :
select
id,
act_invalidation_id,
last_modification_date,
title,
case when act_invalidation_id is null then 1 else 0 end as test
from act order by test, last_modification_date desc
The actual translation
Root<Act> act = query.from(Act.class);
builder.selectCase()
.when(builder.isNull(actRoot.get("actInvalidation")), 1)
.otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);
Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);
query.select(act).orderBy(byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();
I try to create a temporary column (named test) of Integer type and orderby this column, then orderby lastmodificationdate. The content of this new column is determined by the value of actInvalidation field.
In short: How to create a temp column with integer values, then order by this temp column in jpa ?
Thank you

I didn't test this but it should work like this:
Root<Act> act = query.from(Act.class);
Expression<?> test = builder.selectCase()
.when(builder.isNull(actRoot.get("actInvalidation")), 1)
.otherwise(0).as(Integer.class);
Expression<?> actInvalidationPath = actRoot.get("actInvalidation");
Order byInvalidationOrder = builder.asc(actInvalidationPath);
Path<Date> publicationDate = actRoot.get("metadata").get("publicationDate");
Order byLastModificationDate = builder.desc(publicationDate);
Order byTest = builder.asc(test);
query.select(act).orderBy(byTest, byInvalidationOrder, byLastModificationDate);
entityManager.createQuery(query).getResultList();

Related

NHibernate querying with WHERE conditions in pairs

I have a collection of NHibernate objects ConcurrentBag<Event> with properties project_id and name. I want to a set of unrelated (schema wise) objects from another table which also match these properties.
The SQL I would expect would look something like:
SELECT * FROM table WHERE (project_id = 1 AND name = 'foo')
OR (project_id = 2 AND name = 'foo')
OR (project_id = 1 AND name = 'bar')
... etc
The pairs of values in the WHERE clause are based on the values from each Event in the ConcurrentBag<Event>.
I am not sure how to query this with NHibernate (ideally with LINQ). Is this even possible?
This would be difficult with LINQ I think, but if you use QueryOver it's easy to build a WHERE clause dynamically using Restrictions.Disjunction:
var disjunction = Restrictions.Disjunction();
foreach (Event evt in events)
{
disjunction.Add(Restrictions.Where<Table>(
t => t.project_id == evt.project_id && t.name == evt.name);
}
var rows = session.QueryOver<Table>()
.Where(disjunction)
.List<Table>();

Passing different values to the SELECT NEW part of a LINQ query

I am creating a result object from my query, something like this:
var result = from m in MyTable
join r in some_more_tables
select new ResultSummmary
{
Description = m.Description,
start_date = r.start_dat
};
But based on some condition before I get to this query and SELECT NEW, I want to be able to flex what I put in its Description filed, currently it is always m.Description but sometimes I want it to be a static text like "Hospital" and the rest of the times I want it to be m.Description as it is now.
How can we write it that way to be flexible?
Let's pretend the condition is stored in a variable called condition. This would allow you to write the following
var result = from m in MyTable
join r in some_more_tables
select new ResultSummmary
{
Description = condition ? m.Description : "Hospital",
start_date = r.start_dat
};
select new ResultSummmary
{
Description = someBool ? m.Description : "Hospital",
start_date = r.start_dat
};

How to write LINQ IN clause query which will work as LIKE operator as well?

How we can write a LINQ query for following select sql query:
string brandid="1,2,3"
string bodystyleid="1,2,3"
-------------------
-----------------
select * from car
where brandid in (brandid)
and bodystyleid in (brandid)
----------------------
-------------------
My specific requirement is that if brandid or bodystyleid is blank(if user does not select
any checkbox of a particular search option) query should return all record for that particular where condition.
Please guide me.
Thanks,
Paul
In order to fulfil your requirement about returning all items if none are specified, you need to check for the lists being empty.
var brands = brandid.Split(',').Select(x => Int32.Parse(x));
var styles = bodystyleid.Split(',').Select(x => Int32.Parse(x));
var result = from c in car
where (!brands.Any() || brands.Contains(c.brandid))
&& (!styles.Any() || styles.Contains(c.bodystyleid))
select c;
(similar to sgmoore's solution, but includes the check for no brand/style specified)
I've not actually checked how this gets converted back to SQL - it may be more efficient to use a flag to indicate whether there are any values:
var brands = ....; // As above
bool anyBrands = brands.Any()
var result = from c in car
where (!anyBrands || brands.Contains(c.brandid))
.....
Is bodystyleid meant to check brandid or bodystyleid? (I am assuming bodystyleid, however have wrote the query to match the query in the question (brandid))
As a start you could do:
var results = (from c in car
where c.brandid.Contains(brandid)
&& c.bodystyleid.Contains(brandid)
select c).ToList();
var brandids = brandid .Split(',').Select(n => int.Parse(n)).ToList();
var bodyStyleids = bodystyleid.Split(',').Select(n => int.Parse(n)).ToList();
var results =
(from c in car where
brandids.Contains(c.brandid) &&
bodyStyleids.Contains(c.bodystyleid)
select c
).ToList();
the Ids you have are as strings with comma delimiter, you need them to be collections like List of the same type as your Ids of the Car table, so if brandid column is int then brandids has to be List<long>, then you can do
var results = (
from c in cars
where brandids.Contains(c.brandid) && bodystyleid.Contains(c.bodystyleid)
select c).ToList();

Help required to optimize LINQ query

I am looking to optimize my LINQ query because although it works right, the SQL it generates is convoluted and inefficient...
Basically, I am looking to select customers (as CustomerDisplay objects) who ordered the required product (reqdProdId), and are registered with a credit card number (stored as a row in RegisteredCustomer table with a foreign key CustId)
var q = from cust in db.Customers
join regCust in db.RegisteredCustomers on cust.ID equals regCust.CustId
where cust.CustomerProducts.Any(co => co.ProductID == reqdProdId)
where regCust.CreditCardNumber != null && regCust.Authorized == true
select new CustomerDisplay
{
Id = cust.Id,
Name = cust.Person.DisplayName,
RegNumber = cust.RegNumber
};
As an overview, a Customer has a corresponding Person which has the Name; PersonID is a foreign key in Customer table.
If I look at the SQL generated, I see all columns being selected from the Person table. Fyi, DisplayName is an extension method which uses Customer.FirstName and LastName. Any ideas how I can limit the columns from Person?
Secondly, I want to get rid of the Any clause (and use a sub-query) to select all other CustomerIds who have the required ProductID, because it (understandably) generates an Exists clause.
As you may know, LINQ has a known issue with junction tables, so I cannot just do a cust.CustomerProducts.Products.
How can I select all Customers in the junction table with the required ProductID?
Any help/advice is appreciated.
The first step is to start your query from CustomerProducts (as Alex Said):
IQueryable<CustomerDisplay> myCustDisplay =
from custProd in db.CustomerProducts
join regCust in db.RegisteredCustomers
on custProd.Customer.ID equals regCust.CustId
where
custProd.ProductID == reqProdId
&& regCust.CreditCardNumber != null
&& regCust.Authorized == true
select new CustomerDisplay
{
Id = cust.Id,
Name = cust.Person.Name,
RegNumber = cust.RegNumber
};
This will simplify your syntax and hopefully result in a better execution plan.
Next, you should consider creating a foreign key relationship between Customers and RegisteredCustomers. This would result in a query that looked like this:
IQueryable<CustomerDisplay> myCustDisplay =
from custProd in db.CustomerProducts
where
custProd.ProductID == reqProdId
&& custProd.Customer.RegisteredCustomer.CreditCardNumber != null
&& custProd.Customer.RegisteredCustomer.Authorized == true
select new CustomerDisplay
{
Id = cust.Id,
Name = cust.Person.Name,
RegNumber = cust.RegNumber
};
Finally, for optimum speed, have LINQ compile your query at compile time, rather than run time by using a compiled query:
Func<MyDataContext, SearchParameters, IQueryable<CustomerDisplay>>
GetCustWithProd =
System.Data.Linq.CompiledQuery.Compile(
(MyDataContext db, SearchParameters myParams) =>
from custProd in db.CustomerProducts
where
custProd.ProductID == myParams.reqProdId
&& custProd.Customer.RegisteredCustomer.CreditCardNumber != null
&& custProd.Customer.RegisteredCustomer.Authorized == true
select new CustomerDisplay
{
Id = cust.Id,
Name = cust.Person.Name,
RegNumber = cust.RegNumber
};
);
You can call the compiled query like this:
IQueryable<CustomerDisplay> myCustDisplay = GetCustWithProd(db, myParams);
I'd suggest starting your query from the product in question, e.g. something like:
from cp in db.CustomerProducts
join .....
where cp.ProductID == reqdProdID
As you have found, using a property defined as an extension function or in a partial class will require that the entire object is hydrated first and then the select projection is done on the client side because the server has no knowledge of these additional properties. Be glad that your code ran at all. If you were to use the non-mapped value elsewhere in your query (other than in the projection), you would likely see a run-time exception. You can see this if you try to use the Customer.Person.DisplayName property in a Where clause. As you have found, the fix is to do the string concatenation in the projection clause directly.
Lame Duck, I think there is a bug in your code as the cust variable used in your select clause isn't declared elsewhere as a source local variable (in the from clauses).

How can I get my orderby to work using an anonymous type?

What do I put in my order by?? I want to order by Name. I have moved the orderby after the distinct because I read that it needs to be done last.
var result = (from r in db.RecordDocs
where r.RecordID == recordID
select new
{
DocTypeID = r.Document.DocType.DocTypeID,
Name = r.Document.DocType.Name,
Number = r.Document.DocType.Number
}
).Distinct().OrderBy( );
Just do
.OrderBy(doc => doc.Name)
Another option, if you really prefer the query expression syntax would be to chain your query construction across multiple statements:
var query = from r in db.RecordDocs
where r.RecordID == recordID
select new
{
DocTypeID = r.Document.DocType.DocTypeID,
Name = r.Document.DocType.Name,
Number = r.Document.DocType.Number
};
query = query.Disctinct();
query = from doc in query orderby doc.Name select doc;
Since all of these methods are deferred, this will result in the exact same execution performance.

Resources