Using LINQ in CRM 2013

There are few ways we can make use of LINQ to write queries against CRM.

Using the early bound entity classes along with the generated service context

Use the CrmSvcUtil tool to generated the early bound entity classes and service context

CrmSvcUtil.exe /url:http://<serverName>/<organizationName>/XRMServices/2011/Organization.svc

/out:<outputFilename>.cs /username:<username> /password:<password> /domain:<domainName>

/namespace:<outputNamespace> /serviceContextName:<serviceContextName>

 

Uri organizationUri = new Uri("http://server/orgname/XRMServices/2011/Organization.svc");
 Uri homeRealmUri = null;</pre>
<pre> ClientCredentials credentials = new ClientCredentials();
 credentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password", "domain");
 OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
 orgProxy.EnableProxyTypes();
 IOrganizationService _service = (IOrganizationService)orgProxy; 
 
 var xrmServiceContext = new XrmServiceContext(_service);
 // get all contact record that has first name as Hugh
 var lstContact = (from c in xrmServiceContext.ContactSet
 where c.FirstName == "Hugh"
 select c).ToList();
 foreach(var contact in lstContact)
 {
 MessageBox.Show(contact.FullName);
 }


Using Early bound entity classes and OrganizationServiceContext

Suppose we have the early bound entity classes but haven’t generated the service context. In this case we can use OrganizationServiceContext

 


var xrmServiceContext = new OrganizationServiceContext(_service);

var lstContact = (from c in xrmServiceContext.CreateQuery<Contact>()
 where c.FirstName == "Hugh"
 select c).ToList();

foreach (var contact in lstContact)
 {
 MessageBox.Show(contact.FullName);
 }

Using Late bound and OrganizationServiceContext

Suppose we are not generating the early bound classes and using late binding

 

 


  var xrmServiceContext = new OrganizationServiceContext(_service);

 var lstContact = (from c in xrmServiceContext.CreateQuery("contact")
 where c["firstname"] == "Hugh"
 select c).ToList();

 foreach (var contact in lstContact)
 {
 MessageBox.Show(contact["fullname"].ToString());
 }

Hope it helps..

 


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

2 thoughts on “Using LINQ in CRM 2013”

Share your thoughts

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