Search code examples
content-management-systemorchardcms

How to fetch table data from database in Orchard CMS?


How to fetch table data from database in Orchard CMS ? I am a beginner in Orchard CMS, I don't know to fetch and save any data in Orchard CMS, because it is not like a regular database accessing model like ado.net or linq to sql or entity framwork.


Solution

  • Okay, so I would recommend starting off by reading the docs and following some tutorials (eg. http://www.ideliverable.com/blog/writing-an-orchard-webshop-module-from-scratch-part-1). I at least found Orchard a bit tough to jump into and had to sort of wade in slowly, reading all the relevant material. Once you have a bit of an idea about what the hell is going on, the best resource to get to grips with the intricacies of Orchard is to look for examples in Orchards source code.

    Anyway, you are talking about two different things here, accessing Orchard content items and accessing your own tables in Orchard. Both are relatively simple. Orchard has a bunch of nice helper methods to do so. For accessing Orchard content you will want to use the orchard content manager.

    private readonly IOrchardServices services;
    
    public AdminController(IOrchardServices services) {
       this.services = services;
    }
    

    So we now have the OrchardServices in our controller and can use it like so...

    var contentId = 12;
    var contentItem = this.services.ContentManager.Get(contentId);
    

    This will get the content item from the specified id. Say if you wanted to get all content items with a part called MyPart, you could do this:

    var items = this.services.ContentManager.Query<MyPart>().List();
    

    It has a bunch of other methods for creating content etc. Now for querying your own tables, you can use repositories. So say you have a model called FooRecord, you can do this.

    private readonly IRepository<FooRecord> fooRepository;
    
    public AdminController(IRepository<FooRecord> fooRepository) {
       this.fooRepository = fooRepository;
    }
    

    You can query it using linq expressions like this:

    var foo = fooRepository.Fetch(x => x.Id == fooId).FirstOrDefault();
    

    To create a record you can do...

    var record = new FooRecord() { FooName = "Bob" };
    this.fooRepository.Create(record);
    

    Simples! Hope this helps get you started :)

    EDIT:

    So to get part data from a content item you can use .As<> eg.

    var fooPart = contentItem.As<FooPart>();
    var name = fooPart.Name;