Kentico 10 ObjectQuery join multiple tables - kentico

I am basically trying to run a query that gives me all the Users that have purchased a product with a particular SKU. Essentially this SQL here:
SELECT u.FirstName, u.LastName, u.Email
FROM COM_OrderItem oi INNER JOIN COM_Order o ON oi.OrderItemOrderID = o.OrderID
INNER JOIN COM_Customer c ON o.OrderCustomerID = c.CustomerID
INNER JOIN CMS_User u ON c.CustomerUserID = u.UserID
WHERE oi.OrderItemSKUID = 1013
I was trying to use the ObjectQuery API to try and achieve this but have no idea how to do this. The documentation here does not cover the specific type of scenario I am looking for. I came up with this just to try and see if it works but I don't get the three columns I am after in the result:
var test = OrderItemInfoProvider
.GetOrderItems()
.Source(orderItems => orderItems.Join<OrderInfo>("OrderItemOrderID", "OrderID"))
.Source(orders => orders.Join<CustomerInfo>("OrderCustomerID", "CustomerID"))
.Source(customers => customers.Join<UserInfo>("CustomerUserID", "UserID"))
.WhereEquals("OrderItemSKUID", 1013).Columns("FirstName", "LastName", "Email").Result;
I know this is definitely wrong and I would like to know the right way to achieve this. Perhaps using ObjectQuery is not the right approach here or maybe I can somehow just use raw SQL. I simply don't know enough about Kentico to understand the best approach here.

Actually, the ObjectQuery you created is correct. I tested it and it is providing the correct results. Are you sure that there are indeed orders in the system, which contain a product with SKUID 1013 (you can check that in the COM_OrderItem database table)?
Also, how are you accessing the results? Iterating through the results should look like this:
foreach (DataRow row in test.Tables[0].Rows)
{
string firstName = ValidationHelper.GetString(row["FirstName"], "");
string lastName = ValidationHelper.GetString(row["LastName"], "");
string email = ValidationHelper.GetString(row["Email"], "");
}

Related

DocumentHelper.GetDocuments().InCategories() API Method not working as intended

I am trying to get documents of given type with assigned category. This is my code:
var inCategoryDocuments = DocumentHelper.GetDocuments("XYZ.MyType").InCategories("CategoryCodeName");
It's result with this query:
SELECT * FROM View_CMS_Tree_Joined AS V WITH (NOLOCK, NOEXPAND) INNER JOIN xyz_MyType AS C WITH (NOLOCK) ON [V].[DocumentForeignKeyValue] = [C].[MyTypeID] AND V.ClassName = N'xyz.MyType' LEFT OUTER JOIN COM_SKU AS S WITH (NOLOCK) ON [V].[NodeSKUID] = [S].[SKUID] WHERE ([DocumentCulture] = N'en-EN' AND 0 = 1)
It looks like this API method (.InCategories()) doing nothing or I am missing something?
Kentico v11.0.26
Is this category assigned to specific site? If so, it wouldn't work, because in your query you didn't specify the site from which you want get documents.
You can simply add
.OnCurrentSite()
to your DataQuery, it will look like this
var inCategoryDocuments = DocumentHelper.GetDocuments("XYZ.MyType").OnCurrentSite().InCategories("CategoryCodeName");
It will retrieve the documents from the current website based on domain.
IMO method .InCategory shouldn't take care about site or it should be parametrized.
You need to include the using statement for it to work because those methods are extensions.
using CMS.DocumentEngine;

ServiceStack OrmLite - Is it possible to do a group by and have a reference to a list of the non-grouped fields?

It may be I'm still thinking in the Linq2Sql mode, but I'm having a hard time translating this to OrmLite.
I have a customers table and a loyalty card table.
I want to get a list of customers and for each customer, have a list of express cards.
My strategy is to select customers, join to loyalty cards, group by whole customer table, and then map the cards to a single property on customer as a list.
Things are not named by convention, so I don't think I can take advantage of the implicit joins.
Thanks in advance for any help.
Here is the code I have now that doesn't work:
query = query.Join<Customer, LoyaltyCard>((c, lc) => c.CustomerId == lc.CustomerId)
.GroupBy(x => x).Select((c) => new { c, Cards = ?? What goes here? });
Edit: I thought maybe this method:
var q = db.From<Customer>().Take(1);
q = q.Join<Customer, LoyaltyCard>().Select();
var customer = db.SelectMulti<Customer,LoyaltyCard>(q);
But this is giving me an ArgumentNullException on parameter "key."
It's not clear from the description or your example code what you're after, but you can fix your SelectMulti Query with:
var q = db.From<Customer>()
.Join<Customer, LoyaltyCard>();
var results = db.SelectMulti<Customer,LoyaltyCard>(q);
foreach (var tuple in results)
{
Customer customer = tuple.Item1;
LoyaltyCard custCard = tuple.Item2;
}

Astyanax parepared statement withvalues() not working properly

today I migrated to Astyanax 1.56.42 and discovered, that withValues() on prepared statements doesn't seem to work properly with SQL SELECT...WHERE...IN ().
ArrayList<ByteBuffer> uids = new ArrayList<ByteBuffer>(fileUids.size());
for (int i = 0; i < fileUids.size(); i++) {
uids.add(ByteBuffer.wrap(UUIDtoByteArray(fileUids.get(i)), 0, 16));
}
result = KEYSPACE.prepareQuery(CF_FILESYSTEM)
.withCql("SELECT * from files where file_uid in (?);")
.asPreparedStatement()
.withValues(uids)
.execute();
If my ArrayList contains more than one entry, this results in error
SEVERE: com.netflix.astyanax.connectionpool.exceptions.BadRequestException: BadRequestException: [host=hostname(hostname):9160, latency=5(5), attempts=1]InvalidRequestException(why:there were 1 markers(?) in CQL but 2 bound variables)
What am I doing wrong? Is there any other way to handle a SQL SELECT...WHERE...IN () - statement or did I find a bug?
Best regards
Chris
As you mentioned because you are supplying a collection (ArrayList) to a single ? Astyanax throws an exception. I think you need to add a ? for each element you want to have inside the IN clause.
Say you want to have 2 ints stored in an ArrayList called arrayListObj the where clause, your statement looks like this:
SELECT & FROM users WHERE somevalue IN (arrayListObj);
Because you are suppling a collection, this cant work, so you will need multiple ?'s. I.e. you want :
SELECT name, occupation FROM users WHERE userid IN (arrayListObj.get(0), arrayListObj.get(1));
I couldn't find anything on the Astyanax wiki about using the IN clause with prepared statements.

In a master detail relationship how to get a list of master entities without detail entities crm 2011?

I'm using CRM 2011 and I have a 1-n relationship between EntityA(master) and EntityB(detail).
I need to get the list of EntityA records that are not related to any EntityB records. How can I accomplish this inside a plugin using query expression?
I believe this should work (See the EDIT, it doesn't work):
var qe = new QueryExpression("entitya");
var entityBLink = qe.AddLink("entityb", "entityaid", "entityaid", JoinOperator.LeftOuter);
entityBLink.LinkCriteria.AddCondition("entitybid", ConditionOperator.Null);
It should create a SQL Statement that looks something like this:
SELECT
FROM entitya
LEFT OUTER JOIN entityb on entitya.entityaid = entityb.entityaid
AND ( entityb.entitybid IS NULL )
EDIT - Working version
var qe = new QueryExpression("entitya");
var entityBLink = qe.AddLink("entityb", "entityaid", "entityaid", JoinOperator.LeftOuter);
entityBLink.Columns.AddColumn("entitybid");
var entities = service.RetrieveMultiple(qe).Entities.
Where(e => !e.Attributes.Keys.Any(k => k.EndsWith(".entitybid"))).
Select(e => e.ToEntity<entitya>());
The SQL statement for the first query does get generated as is, but since the null check is on the join and it is a left join, all EnityA entities get returned.
The bad news is in CRM there is no way to perform a sub query, or specify in the where clause, a linked entity's properties. I really hope Microsoft spends some time with the next major release adding this type of functionality.
You can however perform the filter on the client side, which is what the C# code is doing above.

Search query with Subsonic

Ok,
Today I am trying to learn Subsonic. Pretty cool stuff.
I am trying to build some search functionality into my website but am struggling about how I might achieve this in Subsonic.
I have one search field that could contain multiple keywords. I want to return results that match all of the keywords. The target on the search is a single text column.
So far I have this (it runs but never returns results):
return new SubSonic.Select().From(Visit.Schema)
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where(InfopathArchive.XmlDocColumn).Like(keywords)
.ExecuteTypedList<Visit>();
There is a one to one mapping between the Visit table and the InfoPathArchive table. I just want to return the collection of Visits that have the keywords in the related XMLDocColumn.
If I could get that working it would be great. Now the second problem is that if someone searches for 'australia processmodel' then obviously the above code should only return that exact phrase. How can I create a query that splits up my search term so that it must return documents that contain ALL of the individual search terms?
Any help appreciated.
Edit: Ok, so the basic search works, but the multiple keyword search doesnt. I did what Adam suggested but it seems Subsonic only uses one parameter for the query.
Here is the code:
List<string> wordsInQueryList = keywords.Split(' ').ToList();
SqlQuery q = Select.AllColumnsFrom<Visit>()
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where(Visit.IsDeletedColumn).IsEqualTo(false);
foreach(string wordInQuery in wordsInQueryList)
{
q = q.And(InfopathArchive.XmlDocColumn).Like("%" + wordInQuery + "%");
}
return q.ExecuteTypedList();
Then if I look at the query that Subsonic generates:
SELECT (bunch of columns)
FROM [dbo].[Visit]
INNER JOIN [dbo].[InfopathArchive] ON [dbo].[Visit].[VisitId] = [dbo].[InfopathArchive].[VisitId]
WHERE [dbo].[Visit].[IsDeleted] = #IsDeleted
AND [dbo].[InfopathArchive].[XmlDoc] LIKE #XmlDoc
AND [dbo].[InfopathArchive].[XmlDoc] LIKE #XmlDoc
So it ends up that only the last keyword is being searched for.
Any ideas?
First question:
return new SubSonic.Select().From(Visit.Schema)
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where(InfopathArchive.XmlDocColumn).Like("%" + keywords + "%")
.ExecuteTypedList<Visit>();
Second question:
Pass a List of words in your query to a function that builds a SubSonic query as follows
SqlQuery query = DB.Select().From(Visit.Schema)
.InnerJoin(InfopathArchive.VisitIdColumn, Visit.VisitIdColumn)
.Where("1=1");
foreach(string wordInQuery in wordsInQueryList)
{
query = query.And(InfopathArchive.XmlDocColumn).Like("%" + wordInQuery + "%")
}
return query.ExecuteTypedList<Visit>();
Obviously this is untested but it should point you in the right direction.
You can do what Adam is suggesting or with 2.2 you can simply use "Contains()" instead of Like("%...%"). We also support StartsWith and EndsWith() :)

Resources