Like the example I used with QueryExpression, you’ll see the difference of using LINQ to query Dynamics CRM data.
- Follow the first 4 steps in the previous post on using QueryExpression to find a user’s roles and teams. The Console Application, Program.cs should look like this:
- Use the following LINQ query statement using late binding to find a CRM user by their email address (internalemailaddress).
<pre>var systemUserLinq = from u in context.CreateQuery("systemuser") where (string)u["internalemailaddress"] == "homer@simpson.com" select new { UserId = u["systemuserid"], FirstName = u["firstname"], LastName = u["lastname"] };</pre>
Alternatively, you can write the LINQ query statement using the GetAttributeValue method
<pre>var systemUserLinq = from u in context.CreateQuery("systemuser") where ((string)u["internalemailaddress"]).Equals("homer@simpson.com") select new { UserId = u.GetAttributeValue<Guid>("systemuserid"), FirstName = u.GetAttributeValue<string>("firstname"), LastName = u.GetAttributeValue<string>("lastname") };</pre>
- Use the following code to loop through the systemUserLinq query results and output the first and last name as well as the systemuserid.
<pre>foreach (var u in systemUserLinq) { Console.WriteLine(u.FirstName + " " + u.LastName + ":" + u.UserId); }</pre>
Build the solution and the output should look like this:
- Within the foreach loop, add the following LINQ query statement to query the roles of the CRM user and output the roles to the console.
<pre>var rolesLinq = from r in context.CreateQuery("role") join sr in context.CreateQuery("systemuserroles") on r["roleid"] equals sr["roleid"] where ((Guid)sr["systemuserid"]).Equals(u.UserId) select new { Name = r["name"] }; foreach (var r in rolesLinq) { Console.WriteLine(r.Name); }</pre>
Build the solution and the output should look like this:
- The LINQ query statement isn’t much different from the roles, use the following LINQ query statement and output the teams to the console.
<pre>var teamsLinq = from t in context.CreateQuery("team") join tm in context.CreateQuery("teammembership") on t["teamid"] equals tm["teamid"] where ((Guid)tm["systemuserid"]).Equals(u.UserId) select new { Name = t["name"] }; foreach (var t in teamsLinq) { Console.WriteLine(t.Name); }</pre>
Build the solution and the output should look like this: