简体   繁体   中英

SQL Server Express dev setup - access denied whack-a-mole

I have a development environment in which I need to use IIS and SQL Server Express. My connection string looks like this:

<add name="DefaultConnection" 
     connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyProject.mdf;Integrated Security=True;User Instance=True" 
     providerName="System.Data.SqlClient" />

This works great when I run the app and browse to the site. Data is returned from the database and I can log into Management Studio and view that data. The problem is when I try to push a new data migration using Update-Database .

I then get this error message:

Login failed for user 'AzureAD\\MyAccount'

If I remove User Instance=True from my connection string, the Update-Database command suddenly works! Then I refresh my page and see the following error from all endpoints that require the database:

CREATE DATABASE permission denied in database 'master'.

I have already tried the trick of deleting this folder. It did not solve it.

C:\Users\MyAccount\AppData\Local\Microsoft\Microsoft SQL Server Data

What gives?

Figured this out so Ill leave the answer here for the next dev:

As I mentioned, my dev setup is running IIS and SQL Express.

  1. Update the connection string to point to an Initial Catalog=MyDatabase instead of the AttachDbFilename=|DataDirectory|\\MyProject.mdf
  2. Remove User Instance=True . Your connection string now looks like:

Data Source=.\\SQLEXPRESS;Initial Catalog=FullStackFitness;Integrated Security=True

  1. Create the database by running Update-Database .
  2. Create a SQL login for the app pool account (IIS APPPOOL\\ACCOUNT) dbcreator and sysadmin on the database.

I did not test it but I believe you can keep using an mdf file and still get this to work by running only steps 2 - 4.

Troubleshooting Tips

Help troubleshooting the access denied issue came from a tip on Scott Allens blog :

The first step I would recommend is trying to determine what connection string the framework is using, because the exception doesn't tell you the connection string, and the connection string can be controlled by a variety of conventions, configurations, and code.

To find out the connection string, I'd add some logging to a default constructor in my DbContext derived class.

public class DepartmentDb : DbContext 
{
    public DepartmentDb() 
    {
       Debug.Write(Database.Connection.ConnectionString);
    }

    public DbSet<Person> People { get; set; }
 }

Run the application with the debugger and watch the Visual Studio Output window. Or, set a breakpoint and observe the ConnectionString property as you go somewhere in the application that tries to make a database connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM