Dynamics CRM 4.0

Using DataContext to execute CRM Service Request – MSCRM 4.0 XRM

Ever since the Microsoft released XRM API for MSCRM 4.0, I have been loving it. The code I wrote looks better without the horrible fetchXml and loosely typed DynamicEntity. However, the XRM API has its own limitations, and there are things that it can’t do. This post will discuss how you can ‘kinda’ use XRM DataContext to execute special requests.

The magic method here is DataContext.UsingService() which takes an action or function as a parameter.

SetStateDynamicRequest

This is one of the most common service request that we cannot do using XRM API. But here is a snippet how you can make the best of both worlds.

DataContext.UsingService(service =>;
	{   
		SetStateDynamicEntityRequest req = new SetStateDynamicEntityRequest();
		req.Entity = new Moniker("new_product", crmProductToDisable.new_productid)
		req.Status = 2;
		req.State = "Inactive"; //inactive
		service.Execute(req);
	});
FetchXml
The all powerful FetchXml can also be used using this method. In the example below, we are retrieving many-to-many relationship using fetchXml.
string fetchXml =
	@"<fetch mapping=""logical"">
	<entity name=""_entity1_entity2"">
	<attribute name=""entity2id"" />
	<attribute name=""entity1_entity2id"" />
	<attribute name=""entity1id"" />
	</entity>
	</fetch>";
string results = "";
	DataContext.UsingService(srv =>
		results = srv.Fetch(fetchXml));

And while we are on this subject, this is how to parse the results using Xml.Linq

XElement xs = XElement.Parse(results);
var relationships =
    (from x in xs.Elements("result")
    select new
    {
         Id = new Guid(x.Element("entity1_entity2id").Value),
         Entity1Id = new Guid(x.Element("entity1id").Value),
         Entity2Id = new Guid(x.Element("entity2id").Value)
    }).ToList();
Cheers – Sy
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s