In a master detail relationship how to get a list of master entities without detail entities crm 2011? - dynamics-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.

Related

Kentico 10 ObjectQuery join multiple tables

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"], "");
}

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;

Orchard: In what table is the Blog post stored

I'm attempting to export data from an older Orchard db and am having problems finding which table the content of a blog post is stored. I've tried using a number of different 'Search all columns' spocs to search all tables and columns but am not finding text from the post itself.
If I have a blog post where the opening sentence is:
This sentence contains a unique word.
I would have expected at least one of the various 'Search all columns' examples to have turned up a table/column. But so far, none have.
thx
Orchard store data based on two tables, ContentItemRecord and ContentItemVersionRecord, which store meta data for content items like BlogPost, and these content items built from multiple parts, each part has it's table and the relation between the item and it's parts is based on Id (if not draftable) or ContentItemRecord_Id (if draftable) columns
if we take BlogPost type as example, which built from TitlePart, BodyPart, AutoroutePart and CommonPart, and you want to select all the data of post (id = 90), then you can find it's title in TitlePartRecord table (ContentItemRecord_Id = 90), and the body text of it in BodyPartRecord table with same relation as title part record, and the route part in AutorouteRecord table with same relation, and the common meta data in CommonPartRecord (Id = 90).
This is the way to extract data from Orchard database, hope this will help you.
Tnx to #mdameer...
and the related query of madmeer's answer is this:
SELECT * FROM dbo.default_Title_TitlePartRecord
inner join dbo.default_Orchard_Framework_ContentItemRecord on
dbo.default_Title_TitlePartRecord.ContentItemRecord_id=dbo.default_Orchard_Framework_ContentItemRecord.Id
inner join dbo.default_Common_BodyPartRecord on
dbo.default_Common_BodyPartRecord.ContentItemRecord_id=dbo.default_Orchard_Framework_ContentItemRecord.Id
where dbo.default_Title_TitlePartRecord.ContentItemRecord_id=90
and this is the rightsolution
Just in case it may be useful for others, the following is the actual SQL query used to migrate an Orchard instance to Umbraco. It is derived from the excellent answers by mdameerand and Iman Salehi:
SELECT t.Title, f.Data, b.Text FROM dbo.Title_TitlePartRecord t
inner join dbo.Orchard_Framework_ContentItemRecord f on
t.ContentItemRecord_id=f.Id
inner join dbo.Common_BodyPartRecord b on
b.ContentItemRecord_id=f.Id
AND b.Id = (
SELECT MAX(m2.Id)
FROM dbo.Common_BodyPartRecord m2
WHERE m2.ContentItemRecord_id = f.Id
)
AND t.Id = (
SELECT MAX(m2.Id)
FROM dbo.Title_TitlePartRecord m2
WHERE m2.ContentItemRecord_id = f.Id
)

loopback relational database hasManyThrough pivot table

I seem to be stuck on a classic ORM issue and don't know really how to handle it, so at this point any help is welcome.
Is there a way to get the pivot table on a hasManyThrough query? Better yet, apply some filter or sort to it. A typical example
Table products
id,title
Table categories
id,title
table products_categories
productsId, categoriesId, orderBy, main
So, in the above scenario, say you want to get all categories of product X that are (main = true) or you want to sort the the product categories by orderBy.
What happens now is a first SELECT on products to get the product data, a second SELECT on products_categories to get the categoriesId and a final SELECT on categories to get the actual categories. Ideally, filters and sort should be applied to the 2nd SELECT like
SELECT `id`,`productsId`,`categoriesId`,`orderBy`,`main` FROM `products_categories` WHERE `productsId` IN (180) WHERE main = 1 ORDER BY `orderBy` DESC
Another typical example would be wanting to order the product images based on the order the user wants them to
so you would have a products_images table
id,image,productsID,orderBy
and you would want to
SELECT from products_images WHERE productsId In (180) ORDER BY orderBy ASC
Is that even possible?
EDIT : Here is the relationship needed for an intermediate table to get what I need based on my schema.
Products.hasMany(Images,
{
as: "Images",
"foreignKey": "productsId",
"through": ProductsImagesItems,
scope: function (inst, filter) {
return {active: 1};
}
});
Thing is the scope function is giving me access to the final result and not to the intermediate table.
I am not sure to fully understand your problem(s), but for sure you need to move away from the table concept and express your problem in terms of Models and Relations.
The way I see it, you have two models Product(properties: title) and Category (properties: main).
Then, you can have relations between the two, potentially
Product belongsTo Category
Category hasMany Product
This means a product will belong to a single category, while a category may contain many products. There are other relations available
Then, using the generated REST API, you can filter GET requests to get items in function of their properties (like main in your case), or use custom GET requests (automatically generated when you add relations) to get for instance all products belonging to a specific category.
Does this helps ?
Based on what you have here I'd probably recommend using the scope option when defining the relationship. The LoopBack docs show a very similar example of the "product - category" scenario:
Product.hasMany(Category, {
as: 'categories',
scope: function(instance, filter) {
return { type: instance.type };
}
});
In the example above, instance is a category that is being matched, and each product would have a new categories property that would contain the matching Category entities for that Product. Note that this does not follow your exact data scheme, so you may need to play around with it. Also, I think your API query would have to specify that you want the categories related data loaded (those are not included by default):
/api/Products/13?filter{"include":["categories"]}
I suggest you define a custom / remote method in Product.js that does the work for you.
Product.getCategories(_productId){
// if you are taking product title as param instead of _productId,
// you will first need to find product ID
// then execute a find query on products_categories with
// 1. where filter to get only main categoris and productId = _productId
// 2. include filter to include product and category objects
// 3. orderBy filter to sort items based on orderBy column
// now you will get an array of products_categories.
// Each item / object in the array will have nested objects of Product and Category.
}

How to create a dataview In Sharepoint with data from a join query?

I have 3 Lists in Sharepoint.
I want to create a dataview that is a join of 3 tables.
Table1 is joined with Table2 on FieldA
Table 2 is joined to Table3 on FieldB
Table1 has duplicate values in FieldA so I need to only return one value to join with Table2.
In Access my query looks like this:
SELECT DISTINCT WRK_InputWorkOrders.WorkOrder, Production1.[Part Number], Production1.[Work Order], Production1.Location, StationItems.Station, Production1.Description, Production1.Revision, WRK_InputWorkOrders.Status
FROM StationItems INNER JOIN (WRK_InputWorkOrders INNER JOIN Production1 ON WRK_InputWorkOrders.WorkOrder = Production1.[Work Order]) ON StationItems.Item = Production1.[Part Number]
WHERE (((WRK_InputWorkOrders.Status)<>"closed"));
Is there a way to write sql-like queries for dataviews?
I have Sharepoint Designer 2007 and Access.
The goal is to get a report that a user can view in Internet Explorer.
I have tried using this method. But it returns duplicate records
I found this suggestion. It suggests using an XPath Filter
not(#yourvalue = preceding-sibling::dfs:YourRepeatingRowName/#yourvalue)
But wasn't able to get it to work. I don't know what to enter as YourRepeatingRowName
I found this link. Does anyone know if it can be used to perform such a join?
Your question is more of an ADO.NET question. Unfortunately ADO.NET doesn't have an easy way to do this, which is why companies like bamboo Solutions builds theirCross List Web Part:
http://store.bamboosolutions.com/pc-42-1-cross-list-web-part.aspx
Otherwise I would attempt to use LINQ to query the tables. You might have more luck doing that.
Here is an example of a JOIN query provided by MS (I only changed the first two DataTable lines to represent filling a DataTable with an SPListItemCollection object)
DataTable orders = spListCol1.ToDataTable();
DataTable details = spListCol2.ToDataTable();
var query =
from order in orders.AsEnumerable()
join detail in details.AsEnumerable()
on order.Field<int>("SalesOrderID") equals
detail.Field<int>("SalesOrderID")
where order.Field<bool>("OnlineOrderFlag") == true
&& order.Field<DateTime>("OrderDate").Month == 8
select new
{
SalesOrderID =
order.Field<int>("SalesOrderID"),
SalesOrderDetailID =
detail.Field<int>("SalesOrderDetailID"),
OrderDate =
order.Field<DateTime>("OrderDate"),
ProductID =
detail.Field<int>("ProductID")
};
DataTable orderTable = query.CopyToDataTable();
Microsoft has a video demo and a writeup that may be just what you want:
Display data from multiple sources in a single Data View
http://office.microsoft.com/en-us/sharepointdesigner/HA103511401033.aspx
With Microsoft Office SharePoint Designer 2007, you can link two or more data sources that contain related data and then create a single Data View that displays data from those linked data sources.
you want to show the query result in SharePoint Designer? I believe, SPD has merged data sources. Look into that.
I found this third part add on
Enesys RS Data Extension lets you query (retrieve, join, merge,...) data from any SharePoint list and use the result for building "Reporting Services" reports as you would do with any other data sources. http://www.enesyssoftware.com/
I can't use it because I am currently running the basic Sharepoint version that uses the internal database.
I've done something like this, but I wasn't able to use a dataview. I ended up writing a custom web part to do it. The approach was:
Use an SPQuery object to get an SPListItemCollection for each list. Use the CAML query to restrict the items returned.
Use the SPListItemCollection object's GetDataTable() method to retrieve an ADO.NET DataTable object for each list.
Add the tables to a DataSet object.
Create relationships between the tables.
Render the data however you like, using DataList or Repeater or whatever.
Here's some code that shows the broad strokes:
protected DataTable GetDataTableFromQuery(string camlQry, SPList theList) {
SPQuery listQry = new SPQuery();
listQry.Query = camlQry;
SPListItemCollection listItems = theList.GetItems(listQry);
return listItems.GetDataTable();
}
protected void BuildDataSet() {
// get SPList objects for the lists in questions ... left as an exercise for the dev -- call them list1, list2, and list3
string camlQry = "the CAML necessary to retreive the ites from list1";
DataTable table1 = GetDataTable(camlQry, list1);
table1.TableName = "Table1";
camlQry = "the CAML necessary to retreive the ites from list2";
DataTable table2 = GetDataTable(camlQry, list2);
table1.TableName = "Table2";
camlQry = "the CAML necessary to retreive the ites from list3";
DataTable table3 = GetDataTable(camlQry, list3);
table1.TableName = "Table3";
// now build the DataSet
DataSet ds = new DataSet();
ds.Tables.Add(table1);
ds.Tables.Add(table2);
ds.Tables.Add(table3);
ds.Relations.Add("Table1_2", ds.Tables["Table1"].Columns["FieldA"], ds.Tables["Table2"].Columns["FieldA"]);
ds.Relations.Add("Table2_3", ds.Tables["Table2"].Columns["FieldB"], ds.Tables["Table3"].Columns["FieldB"]);
// now you can do something with these, like store them in the web part class and bind them to repeaters in the web part's Render() method
}

Resources