Wednesday, March 1, 2017

Using DocumentDB with C# my Way

After struggling several weeks trying to come up with the correct syntax using DocumentDB, C#, and MVC I finally got it.

I like to create an IO class that contains all the methods for CRUD and Queries. My Controllers call these methods for all data io. The nice thing is that you can start out with a single project and then create a DLL or API later and the controller does not have to change.

There are plenty of examples out there including the QuickStart app created in the portal. I could not get most of these to work properly. I assume that the database and collection have already been created in the portal. So here is my solution...

Sample IO and Controller Class:

public class ioPt
    {
        private const string EndpointUri = "https://yourid.documents.azure.com:443/";
        private const string PrimaryKey = "yourkey";
        private static readonly string DatabaseId = "yourdatabase";
        private static readonly string CollectionId = "yourcollection";
        private static readonly Uri CollectionLink = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);

        public List<ptTenant> TenantList()
        {
            using (var _client = new DocumentClient(new Uri(EndpointUri), PrimaryKey))
            {
                var data = _client.CreateDocumentQuery<ptTenant>(CollectionLink).Where(x => x.TypeId == nameof(ptTenant))
                    .OrderBy(x => x.Name).ToList();
                return data;
            }
        }

        public async Task<ptTenant> TenantAdd(ptTenant tenant)
        {
            using (var _client = new DocumentClient(new Uri(EndpointUri), PrimaryKey))
            {
                await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), tenant);
            }
            return tenant;
        }
    }

 public class HostController : Controller
    {
        ioPt zio = new ioPt();

        public ActionResult Index()
        {
            var data = zio.TenantList();
            return View(data);
        }

        public IActionResult NewTenant()
        {
            var tenant = new ptTenant();
            return View(tenant);
        }

        [HttpPost]
        public async Task<ActionResult> NewTenant(ptTenant tenant)
        {
            if (ModelState.IsValid)
            {
                await zio.TenantAdd(tenant);
                return RedirectToAction("Index");
            }
            return View(tenant);
        }

    }