title: How to fix 'CREATE SCHEMA' failed error when running EF Code First migrations with Azure Managed Identity
body: <p>I am trying to run EF6 Code First migrations against an Azure SQL database connecting via Azure Managed Identity. There are several migrations to run. The last migration fails. This migration is different to the others because it creates tables in a new schema.</p>
  
  <p>This is the error which is returned when running the Entity Framework Code First migration which creates the new schema:</p>
  
  <pre><code>System.Data.SqlClient.SqlException: The specified schema name "uuid@uuid" either does not exist or you do not have permission to use it.
  CREATE SCHEMA failed due to previous errors.
  </code></pre>
  
  <p>I have logged the SQL commands on the database and the command which appears to be failing is</p>
  
  <pre><code>IF schema_id('MyNewSchema') IS NULL
  EXECUTE('CREATE SCHEMA [MyNewSchema]')
  </code></pre>
  
  <p>With the error:    </p>
  
  <pre><code>&lt;batch_information&gt;&lt;failure_reason&gt;Err 2759, Level 16, Server mysqldbname
  CREATE SCHEMA failed due to previous errors.&lt;/failure_reason&gt;&lt;/batch_information&gt;
  </code></pre>
  
  <p>Here are some details on the system:</p>
  
  <ul>
  <li>All other migrations before this one succeeded. However, none of those needed to create a new schema</li>
  <li>Using .NET Framework 4.7.1. EF6.2.0.</li>
  <li>Using Azure SQL database.</li>
  <li>Connecting to Azure SQL from an ASP.NET MVC web application using Azure Managed Identity (<a href="https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi</a>).</li>
  </ul>
  
  <p><strong>Things I've tried</strong></p>
  
  <p><em>1. Adding roles</em></p>
  
  <p>The main thing I've tried is using the Microsoft permissions docs to work out what permissions are needed. So far I have added the following roles to the contained user which the App Service running migrations connects as:</p>
  
  <pre><code>db_ddladmin
  db_datareader
  db_datawriter
  db_securityadmin
  db_owner
  db_accessadmin
  </code></pre>
  
  <p>(Note that the other migrations worked fine with just db_ddladmin, db_datareader and db_datawriter)</p>
  
  <p><em>2. Running migrations as server admin</em></p>
  
  <p>I have tried running the migrations as the SQL Server admin user. This works, but we are not allowed to connect as the SQL Server admin user for the production system.</p>