programing

데이터베이스 'master'에서 CREATE DATABASE 권한이 거부되었습니다 (EF 코드 우선).

itsource 2021. 1. 14. 08:17
반응형

데이터베이스 'master'에서 CREATE DATABASE 권한이 거부되었습니다 (EF 코드 우선).


내 프로젝트에서 코드 우선을 사용하고 호스트에 배포하지만 오류가 발생합니다.

데이터베이스 'master'에서 CREATE DATABASE 권한이 거부되었습니다.

이것은 내 연결 문자열입니다.

<add name="DefaultConnection" 
     connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-test-2012615153521;Integrated Security=False" 
     providerName="System.Data.SqlClient;User ID=test;Password=test"/>

거부 된 권한은 보안이므로 "사용자"권한을 추가해야합니다.

  1. 데이터베이스 (.mdf 파일)를 마우스 오른쪽 단추로 클릭 한 다음 속성을 클릭합니다.
  2. 보안 탭으로 이동
  3. 계속 버튼을 클릭
  4. 추가 버튼 클릭
  5. 고급 버튼 클릭
  6. 다른 창이 표시되면 오른쪽에있는 "지금 찾기"버튼을 클릭합니다.
  7. 아래 필드에서 맨 아래로 이동하여 "사용자"를 클릭하십시오. 확인을 클릭하십시오.
  8. 생성 된 "사용자"권한을 클릭 한 다음 모든 권한 확인란을 선택합니다.

됐습니다. 이제 데이터베이스에 대한 권한이 있습니다.


나는 같은 문제가 있었다. 이것은 나를 위해 일한 것입니다.

  1. 이동 SQL Server Management Studio에서 와 같이 실행 관리자 .
  2. 보안 -> 로그인을 선택하십시오.
  3. 로그인에서 데이터베이스에 액세스 할 사용자 이름 또는 사용자를 선택 하고 두 번 클릭합니다.
  4. 데이터베이스를 만들 수있는 자격 증명을 제공 할 서버 역할을 제공합니다. 제 경우에는 public이 이미 확인되었으므로 dbcreatorsysadmin을 확인했습니다 .
  5. 패키지 관리자 콘솔에서 update-database를 다시 실행하십시오. 이제 데이터베이스가 성공적으로 생성되었습니다.

다음은 더 큰 그림을 얻을 수 있도록 이미지입니다. 물론 내 자격 증명을 흐리게 처리했습니다.여기에 이미지 설명 입력


db를 만들 수있는 권한이 있는지 확인하십시오 (user2012810이 언급했듯이).

또는

코드에서 먼저 다른 (또는 기본) 연결 문자열을 사용하는 것 같습니다. 컨텍스트 클래스에 연결 이름을 설정 했습니까?

public class YourContext : DbContext
    {
        public YourContext() : base("name=DefaultConnection")
        {

        }

        public DbSet<aaaa> Aaaas { get; set; }
    }

Code First (데이터베이스 접근 방식없이)를 사용하여 데이터베이스를 만들려고 할 때 동일한 문제가 발생했습니다. 문제는 EF에 데이터베이스를 만들 수있는 권한이 없다는 것입니다.

그래서 Code First (기존 데이터베이스 접근 방식 사용)를 사용하여 작업했습니다.

단계 :

  1. SQL Server Management Studio에서 데이터베이스를 만듭니다 (테이블없이 선호).
  2. 이제 Visual Studio로 돌아가서 서버 탐색기에서 새로 생성 된 데이터베이스의 연결을 추가합니다.
  3. 이제 데이터베이스의 연결 문자열을 사용하고 "Default Connection"과 같은 이름으로 app.config에 추가합니다.
  4. 이제 Context 클래스에서 생성자를 만들고 기본 클래스에서 확장하고 연결 문자열의 이름을 매개 변수로 전달합니다. 처럼,

    public class DummyContext : DbContext
    {
      public DummyContext() : base("name=DefaultConnection")
      {
      }  
    }
    

5. 이제 코드를 실행하고 제공된 데이터베이스에 추가되는 테이블을 확인합니다.


관리자 권한으로 Visual Studio를 실행하십시오.


이 오류는 솔루션에 여러 프로젝트가 있고 잘못된 프로젝트가 시작 프로젝트로 설정된 경우에도 발생할 수 있습니다.

Update-Database에서 사용하는 연결 문자열 은 패키지 관리자 콘솔에서 선택한 "기본 프로젝트"가 아닌 시작 프로젝트에서 제공 되기 때문에 중요합니다 .

( masoud에 대한 크레딧 )


내 방식으로이 문제를 해결했습니다. 다음과 같이 연결 문자열을 시도하십시오.

<add name="MFCConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MFC.mdf;Initial Catalog=MFC;Integrated Security=false;User ID=sa;Password=123"
  providerName="System.Data.SqlClient" />

마스터에서 MFC로 기본 db를 설정하는 것을 잊지 마십시오 (귀하의 경우 aspnet-test-2012615153521).


오류에서 알 수 있듯이 SQL 로그인에는 데이터베이스를 만들 수있는 권한이 없습니다. 로그인에 필요한 역할이있을 때 권한이 부여됩니다. 데이터베이스 생성, 변경 및 삭제 권한이있는 역할은 dbCreator 입니다. 따라서 문제를 해결하려면 로그인에 추가해야합니다. SQL Management Studio에서 사용자를 마우스 오른쪽 단추로 클릭 한 다음 속성> 서버 역할로 이동하여 수행 할 수 있습니다. 나는 똑같은 오류가 발생하고 정확히 그렇게하여 해결했습니다.


연결 문자열을 다시 확인하십시오. 존재하지 않는 데이터베이스를 가리키는 경우 EF는 master데이터베이스에 테이블을 만들려고 시도하며이 오류가 발생할 수 있습니다.
제 경우에는 데이터베이스 이름에 오타가있었습니다.


위의 내용이 합쳐져서 제가해야했던 일을 추가하겠습니다. Code First를 사용하고 있으며 'create-database'를 사용해 보았지만 제목에 오류가 있습니다. 닫히고 다시 열림 (이번에는 관리자 권한으로)-명령이 인식되지 않지만 'update-database'가 그렇게 사용되었습니다. 같은 오류.

이 문제를 해결하기 위해 취한 단계는 다음과 같습니다.

1) SQL Server Management Studio를 열고 "비디오"데이터베이스 생성

2) VS2013에서 서버 탐색기 ( '보기'아래)를 열고 데이터베이스에 연결합니다.

3) 연결-> 속성을 ​​마우스 오른쪽 버튼으로 클릭하고 연결 문자열을 가져 왔습니다.

4) web.config에서 연결 문자열을 추가했습니다.

   <connectionStrings>
<add name="DefaultConnection"
  connectionString="Data Source=MyMachine;Initial Catalog=Videos;Integrated Security=True" providerName="System.Data.SqlClient"
  />
  </connectionStrings>

5) 컨텍스트를 설정하는 곳에서 DefaultConnection을 참조해야합니다.

using System.Data.Entity;

namespace Videos.Models
{
public class VideoDb : DbContext
{
    public VideoDb()
        : base("name=DefaultConnection")
    {

    }

    public DbSet<Video> Videos { get; set; }
}
}

6) 패키지 관리자 콘솔에서 'update-database'를 실행하여 테이블을 만듭니다.

Remember you can use Seed() to insert values when creating, in Configuration.cs:

        protected override void Seed(Videos.Models.VideoDb context)
        {
        context.Videos.AddOrUpdate(v => v.Title,
            new Video() { Title = "MyTitle1", Length = 150 },
            new Video() { Title = "MyTitle2", Length = 270 }
            );

        context.SaveChanges();
        }

Check that the connection string is in your Web.Config. I removed that node and put it in my Web.Debug.config and this is the error I received. Moved it back to the Web.config and worked great.


Run Visual Studio as Administrator and put your SQL SERVER authentication login (who has the permission to create a DB) and password in the connection string, it worked for me


If you're running the site under IIS, you may need to set the Application Pool's Identity to an administrator.


I encountered what appeared to be this error. I was running on windows and found my administrator windows user did not have administrator privileges to database.

  1. Shut down SQL Server from ‘Services’

서비스 비활성화

  1. Open cmd window (as administrator) and run single-user mode as local admin with this command (the version of MSSQL may differ):
"C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\Binn\sqlservr.exe" -m -s SQLEXPRESS
  1. Open another cmd window (as administrator)
  2. Open sqlcmd on that terminal with:
sqlcmd -S .\SQLEXPRESS
  1. Now add the sysadmin role to your user:
sp_addsrvrolemember 'domain\user', 'sysadmin'
GO
  1. Re-enable SQL Server from ‘Services’

Credit to: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/76fc84f9-437c-4e71-ba3d-3c9ae794a7c4/


Step 1: Disconnect from your local account.

Step 2: Again Connect to Server with your admin user

Step 3: Object Explorer -> Security -> Logins -> Right click on your server name -> Properties -> Server Roles -> sysadmin -> OK

Step 4: Disconnect and connect to your local login and create database.


I have no prove for my solution, just assumptions.

In my case it is caused by domain name in connection string. I have an assumption that if DNS server is not available, it is not able to connect to database and thus the Entity Framework tries to create this database. But the permission is denied, which is correct.


The solution that worked for me was to use the Entity Framework connection string that is created when I ran the database first wizard when creating the edmx file. The connection string needs the metadata file references, such as "metadata=res:///PSEDM.csdl|res:///PSEDM.ssdl|res://*/PSEDM.msl". Also, the connection string needs to be in the config of the calling application.

HT to this post for pointing me in that direction: Model First with DbContext, Fails to initialize new DataBase


For me I just close all current session including the SQL Server Management Studio and then I reopened execute the script below works fine

IF EXISTS (SELECT NAME FROM master.sys.sysdatabases WHERE NAME = 'MyDb')
DROP DATABASE mydb RESTORE DATABASE SMCOMDB FROM DISK = 'D:/mydb.bak' 

I had the same problem and I tried everything available on the internet. But SSMS RUN AS ADMINISTRATOR work for me. If you still face some issue, make sure you must have downloaded the SQL SERVER.


The solution to this problem is as simple as eating a piece of cake.This issue generally arises when your user credentials change and SQL server is not able to identify you .No need to uninstall the existing SQL server instance .You can simply install a new instance with a new instance name . Lets say if your last instance name was 'Sqlexpress' , so this time during installation , name your instance as 'Sqlexpress1' . Also don't forget to select the mix mode (i.e Sql Server Authentication & Windows Authentication) during the installation and provide a system admin password which will be handy if such a problem occurs in future. This solution will definitely resolve this issue. Thanks..

참조 URL : https://stackoverflow.com/questions/11231934/create-database-permission-denied-in-database-master-ef-code-first

반응형