title: How to create custom role in azure active directory using graph api?
body: <p>I would like to create custom roles in azure active directory for an application (Application Level).I tried using graph api and i got exception as "The context is already tracking the entity.".I am attaching my code below.Please find what is wrong.Please tell me how to add custom application roles.</p>
  
  <pre><code>    using Microsoft.Azure.ActiveDirectory.GraphClient;
      using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;
      using Microsoft.Owin.Security.OpenIdConnect;
      using System;
      using System.Collections.Generic;
      using System.Configuration;
      using System.Linq;
      using System.Threading.Tasks;
      using System.Web;
      using System.Web.Mvc;
      using WebAppGraphAPI.Utils;
  
      namespace WebAppGraphAPI.Controllers
      {
          public class ApplicationRoleController : Controller
          {
              private static readonly string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
  
              // GET: ApplicationRole
              public async Task&lt;ActionResult&gt; Index()
              {
                  var roleList = new List&lt;AppRole&gt;();
                  try
                  {
                      ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
                      IPagedCollection&lt;IApplication&gt; pagedCollection = await client.Applications.Where(x =&gt; x.AppId == clientId).ExecuteAsync();
  
                      if (pagedCollection != null)
                      {
                          do
                          {
                              List&lt;IApplication&gt; applicationItemList = pagedCollection.CurrentPage.ToList();
                              foreach (IApplication application in applicationItemList)
                              {
                                  roleList.Add((AppRole)application.AppRoles);
                              }
                              pagedCollection = await pagedCollection.GetNextPageAsync();
                          } while (pagedCollection != null &amp;&amp; pagedCollection.MorePagesAvailable);
                      }
                  }
                  catch (Exception e)
                  {
                      if (Request.QueryString["reauth"] == "True")
                      {
                          //
                          // Send an OpenID Connect sign-in request to get a new set of tokens.
                          // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                          // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                          //
                          HttpContext.GetOwinContext()
                              .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                      }
  
                      //
                      // The user needs to re-authorize.  Show them a message to that effect.
                      //
                      ViewBag.ErrorMessage = "AuthorizationRequired";
                      return View(roleList);
                  }
                  return View(roleList);
              }
  
              /// &lt;summary&gt;
              ///     Creates a view to for adding a new &lt;see cref="User" /&gt; to Graph.
              /// &lt;/summary&gt;
              /// &lt;returns&gt;A view with the details to add a new &lt;see cref="User" /&gt; objects&lt;/returns&gt;
              public ActionResult CreateRole()
              {
                  return View();
              }
  
              [HttpPost]
              public async Task&lt;ActionResult&gt; CreateRole(
                  [Bind(
                      Include =
                          "DisplayName,Value"
                      )] AppRole role)
              {
                  ActiveDirectoryClient client = null;
                  try
                  {
                      client = AuthenticationHelper.GetActiveDirectoryClient();
                  }
                  catch (Exception e)
                  {
                      if (Request.QueryString["reauth"] == "True")
                      {
                          //
                          // Send an OpenID Connect sign-in request to get a new set of tokens.
                          // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                          // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                          //
                          HttpContext.GetOwinContext()
                              .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                      }
  
                      //
                      // The user needs to re-authorize.  Show them a message to that effect.
                      //
                      ViewBag.ErrorMessage = "AuthorizationRequired";
                      return View();
                  }
  
                  try
                  {
  ////Get Current application from active directory
                      IPagedCollection&lt;IApplication&gt; pagedCollection = await client.Applications.Where(x =&gt; x.AppId == clientId).ExecuteAsync();
                      var appObject = pagedCollection.CurrentPage.ToList().FirstOrDefault();
                      appObject.AppRoles.Add(role as AppRole);
                      ////
                      ////Am Getting Exception Here as "The context is already tracking the entity."....
                      ////
                      await client.Applications.AddApplicationAsync(appObject);
                      return RedirectToAction("Index");
                  }
                  catch (Exception exception)
                  {
                      ModelState.AddModelError("", exception.Message);
                      return View();
                  }
              }
          }
      }
  </code></pre>