CodeGarden 10: The sixth annual Umbraco Developer Conference
June 23-25th 2010 - free ASP.NET MVC pre-conference. Register today!

DataContext

Pages

The generated DataContext has a lot of similarities with the DataContext in LINQ to SQL, with collections against it which represent the different DocType groups. This starts with a non-hierarchical representation of the Umbraco DocType data so that when you start interrogating the data you're working with the entire collection to start with.
The DataContext is an IDisposable object which handles the connection with the data provider for the instance.
There are two constructors within the DataContext, one which takes an instance of an UmbracoDataProvider, and a default constructor.
The default constructor will pass in an instance of the Umbraco.Core.Linq.Node.NodeDataProvider, using its default constructor.

The DataContext is essentially the work-horse of LINQ to Umbraco as it is the location where all the LINQ queries will start from.

Thread Safety

Like the LINQ to SQL DataContext the LINQ to Umbraco DataContext is not thread safe and extream caution should be taken into consideration when sharing it across mutliple threads.

Because of this thead sharing of the DataContext is not supported.

Examples

Generated Umbraco DataContext

    public partial class MyUmbracoDataContext : UmbracoDataContext
    {

        #region Partials
        partial void OnCreated();
        #endregion


        public MyUmbracoDataContext() :
            base()
        {
            OnCreated();
        }

        public MyUmbracoDataContext(UmbracoDataProvider provider) :
            base(provider)
        {
            OnCreated();
        }

        public Tree CwsTextpages
        {
            get
            {
                return this.LoadTree();
            }
        }
    }

 

Using the Default Constructor



using (var ctx = new MyUmbracoDataContext())
{
    var pages = from page in ctx.CwsTextpages
                where page.Bodytext.Contains("Umbraco is cool")
                select page;
    foreach(var page in pages)
    {
        Console.WriteLine(page.Title);
    }
}