How to use Orchard API for retrieving custom content types?

Topics: Customizing Orchard, General, Writing modules
Feb 22, 2012 at 5:37 PM

I am inheriting some nasty Orchard code that instead of using the Orchard framework, they are querying the database directly to get content like this:

cmd.CommandText = "SELECT civr.Id, rrpr.Title, fcir.Data, rrpr.Slug FROM [td__Orchard_Framework_ContentItemVersionRecord] as civr JOIN [dbo].[td__Routable_RoutePartRecord] as rrpr ON civr.Id=rrpr.Id JOIN [dbo].[td__Orchard_Framework_ContentItemRecord] as fcir ON rrpr.ContentItemRecord_id=fcir.Id JOIN [dbo].[td__Orchard_Framework_ContentTypeRecord] as fctr ON fcir.ContentType_id=fctr.Id WHERE civr.Latest=1 AND civr.Published=1 AND fctr.Name='MyCustomContentType' ORDER BY civr.Id DESC";
using (var reader = cmd.ExecuteReader()) {
  while (reader.Read()) { 
    xml.LoadXml(reader["Data"].ToString());
    XmlNodeList someProp = xml.GetElementsByTagName("Something");
    string title = reader["Title"].ToString(); ...

I am new to Orchard, but surely it has an API so I do not have to go directly to the database. How can I convert the above SQL statement to Orchard's API?

Coordinator
Feb 22, 2012 at 6:39 PM

It seems it's trying to get the "Something" field from the "MyCustomContentType" custom content type. I would do something like this:


var myContents = _contentManager.Query().ForType("MyCustomContentType").OrderBy(x => x.Id);
foreach(dynamic contentItem in myContents) {
  DoSomethingWith(contentItem.MyCustomContentType.Something.Value; // this is using the dynamic behavior to access custom fields
}
 

Coordinator
Feb 22, 2012 at 6:40 PM

Oh, and I assume this code could be replaced by no code at all with the upcoming Projector module.

Mar 31, 2012 at 4:04 PM
sebastienros wrote:

It seems it's trying to get the "Something" field from the "MyCustomContentType" custom content type. I would do something like this:


var myContents = _contentManager.Query().ForType("MyCustomContentType").OrderBy(x => x.Id);
foreach(dynamic contentItem in myContents) {
  DoSomethingWith(contentItem.MyCustomContentType.Something.Value; // this is using the dynamic behavior to access custom fields
}
 

 

@sebastienros: Orchard 1.4 with Projector module is here. But for arguments sake, lets say I still want to get contents writing codes. Also, I would like get items who has "My Value" as the value of field "Something". I can do this by:

var myContents = 
_contentManager
.HqlQuery()
.ForType("MyCustomContentType")
.List()
.Cast<dynamic>
.Where(x => x.MyCustomContentType.Something.Value == "My Value")
.ToList();

But, that would be loading all contents of MyCustomContentType in memory and filtering it then. Can that whole thing be done with HqlQuery so that only the items I desire will be fetched from database?

- Zp Bappi.

Jan 22, 2013 at 5:21 PM
Edited Jan 22, 2013 at 6:52 PM

http://orchard.codeplex.com/discussions/350727