I've set up a (remote) SQL Server Express for my ASP.NET MVC with Entity Framework 4.3 project. On my local machine using SQL Compact everything works fine. When I try to connect to the SQL Express server I got the following error on the call migrator.Update():
The INSERT permission was denied on the object '__MigrationHistory', database 'MyDataBase', schema 'dbo'.
On the server I've done the following:
Created a user with SQL Server credentials
Created a database called MyDataBase
Any ideas?
The DB roles db_denydatareader,db_denydatawriter must be unchecked for the created user.
I was getting this error too. To fix it I added db_owner to my user's "database role membership", and checked the db_owner check box under "schemas owned by this user" (SSMS 2008).
Related
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.
This is the error which is returned when running the Entity Framework Code First migration which creates the new schema:
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.
I have logged the SQL commands on the database and the command which appears to be failing is
IF schema_id('MyNewSchema') IS NULL
EXECUTE('CREATE SCHEMA [MyNewSchema]')
With the error:
<batch_information><failure_reason>Err 2759, Level 16, Server mysqldbname
CREATE SCHEMA failed due to previous errors.</failure_reason></batch_information>
Here are some details on the system:
All other migrations before this one succeeded. However, none of those needed to create a new schema
Using .NET Framework 4.7.1. EF6.2.0.
Using Azure SQL database.
Connecting to Azure SQL from an ASP.NET MVC web application using Azure Managed Identity (https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi).
Things I've tried
1. Adding roles
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:
db_ddladmin
db_datareader
db_datawriter
db_securityadmin
db_owner
db_accessadmin
(Note that the other migrations worked fine with just db_ddladmin, db_datareader and db_datawriter)
2. Running migrations as server admin
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.
If you add AUTHORIZATION to the CREATE SCHEMA command, it works.
So the statement Entity Framework creates need's to look like this instead:
IF schema_id('MyNewSchema') IS NULL
EXECUTE('CREATE SCHEMA [MyNewSchema] AUTHORIZATION [dbo]')
You can do this by overwriting ApplicationSqlServerMigrationsSqlGenerator
protected override void Generate(EnsureSchemaOperation operation, IModel model, MigrationCommandListBuilder builder)
{
if (operation is null)
throw new ArgumentNullException(nameof(operation));
if (builder is null)
throw new ArgumentNullException(nameof(builder));
if (string.Equals(operation.Name, "dbo", StringComparison.OrdinalIgnoreCase))
{
return;
}
var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
builder
.Append("IF SCHEMA_ID(")
.Append(stringTypeMapping.GenerateSqlLiteral(operation.Name))
.Append(") IS NULL EXEC(")
.Append(
stringTypeMapping.GenerateSqlLiteral(
"CREATE SCHEMA "
+ Dependencies.SqlGenerationHelper.DelimitIdentifier(operation.Name)
+ " AUTHORIZATION "
+ Dependencies.SqlGenerationHelper.DelimitIdentifier("dbo")
+ Dependencies.SqlGenerationHelper.StatementTerminator))
.Append(")")
.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator)
.EndCommand();
}
And then registering it:
services.AddDbContextPool<ApplicationDbContext>(options =>
{
options.UseSqlServer("Your connection string");
options.ReplaceService<IMigrationsSqlGenerator, ApplicationSqlServerMigrationsSqlGenerator>();
});
(The code above is for EF Core, as I had the issue there)
I've just run into the same issue using asp.net core 2.2 and EF core. I was trying to use a managed identity to create the schema and got the same error. I found this article which indicates it is a bug - https://techcommunity.microsoft.com/t5/Azure-Database-Support-Blog/Lesson-Learned-54-The-specified-schema-name-name-domain-com/ba-p/369152.
My only workaround has been to create the schema with server admin which isn't ideal.
I am going through the MvcMusicStore tutorial on the www.asp.net website.
I am able to use Entity Framework Core 2.0 and migrations to create a DB in localDb.
Here is the connection string from that in appsettings.json:
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-19840e0a-5fb4-409c-9f38-7f2946cd3937;Trusted_Connection=True;MultipleActiveResultSets=true",
When ever I do these tutorials I usually at this point once the DB is created and everything works switch to SQL Server Express, because this is how I actually develop my projects.
So Entity Framework checks the new connection string, doesn't see the DB exists, and creates the new DB based on the Model.
But I can't seem to get the connection string to SQL Express working.
Here is what I have tried so far:
"MvcMovieContext": "Server=MyComputerName\\SQLEXPRESS;Database=MvcMovie;Trusted_Connection=True;MultipleActiveResultSets=true"
and
"MvcMovieContext": "Data Source=.\\SQLEXPRESS;Initial Catalog=MvcMovie;Integrated Security=True;MultipleActiveResultSets=true"
Both give the same result. The dreaded message:
SqlException: Cannot open database "MvcMovie" requested by the login. The login failed.
Login failed for user 'Domain\smiller'.
I installed SQL Server Express in Mixed Mode so Windows Authentication works and I made my 'Domain\smiller' account a DbCreater in Server Roles.
Just can't seem to get it.
I needed to run:
Update-Database
I went through this last year:
Why is dotnet ef not able to create a database against SQL Server Express?
It seems I never learn.
I am trying connect to firebird 3.0 throught latest version of ADO.NET provider 5.0.5.0 from my simple test .net application. When i used sysdba user connection is made OK, but if i used other user then connection failed with classic FBException :
Your user name and password are not defined. Ask your database administrator to set up a Firebird login.
"initial catalog=c:\\Database\\Data.fdb;data source=localhost;user id=sysdba;password=sysPass;port number=3050" = OK
"initial catalog=c:\\Database\\Data.fdb;data source=localhost;user id=michal;password=micPass;port number=3050" = failed
But if i am trying connect throught IBExpert or isql , then connection is made OK and i can get data from tables.
Previously i used Firebird 2.1 and then i upgraded to Firebird 3.0 superclassic and get ADO.NET provieder from nuget.Actually i do not need SRP ecryption so I disabled WireCrypt etc. and use Legacy authentication (Firebird 3.0 release notes page 117). Then i created my new user via IBExpert (sysdba was created during installation firebird server).
I do not need migrate users from previous firebird version so I skiped Upgrading a v.2.x Security Database steps.
It is strange that i can connect myUser via IBExpert or isql, but not via ADO.NET provider.
It seems to me unlikely that ADO.NET provider has bug of this type (everyone needed connect via user), so I guess that i have some bad configuration.
I had some bad configurations and I need set correctly:
In firebird.conf, there has to be: WireCrypt = Enabled (not disabled)
Create user account older way (in my case via IBExpert)
The password have to max. length 8 chars (previously you can have more chars and Firebird is omit)
I'm trying to setup a local firebird instance to test against but am unable to connect to it with even ISQL. I have tried to following by following the quick start guide here:
CONNECT ..\examples\empbuild\employee.fdb user SYSDBA password masterkey;
Which resulted in:
Statement failed, SQLSTATE = 08001
unavailable database
After some searching I tried modifying that to:
CONNECT "localhost:C:\Program Files\Firebird\Firebird_2_5\examples\empbuild\employee.fdb" user SYSDBA password masterkey;
Which resulted in:
Statement failed, SQLSTATE = 28000
cannot attach to password database
After confirming I had the right directory path I decided to give on on connecting for now and try creating a new DB:
SQL>CREATE DATABASE 'C:\data\test.fdb' page_size 8192
CON>user 'SYSDBA' password 'masterkey';
Which also gave me the error:
Statement failed, SQLSTATE = 08001
unavailable database
Are there any common pitfalls I might be hitting? I've also tried the commands above both with and without the firebird service running. Also is there a detailed reference on the SQLSTATE codes?
As already mentioned in my comments the problem is caused by running the Firebird server as an application. Firebird has its password database (security2.fdb) in C:\Program Files\Firebird\Firebird_2_5. As this database is (almost, but not entirely) a normal Firebird database, the server requires write access to this database (for the transactions, etc).
By default (with UAC) users do not have write access to the password database, so this requires elevation to Administrator. So access to Firebird requires that you either run the application as a service with sufficient rights (eg as done by the default installer), or when running the server as application to run it 'As administrator'. Another option is to not install it in Program Files.
This BTW applies double when accessing the example employee database as this database file is also located in the Program Files folder.
This is for macOS/OSX (mine is 10.15) firebird ver 2.5 users.
The installation process here does not ask for a sysdba password. Which means: the security database 'security2.fdb' does not exist after a new installation.
This seems to be intentionally for security reasons since > ver 2.5.
To create one, we use the demo database as a helper:
open sql as su: >sudo isql (we don't have user rights on dir)
Connect to a existing db:
sql>connect
"/Library/Frameworks/Firebird.framework/Resources/examples/empbuild/employee.fdb
" user 'SYSDBA' password 'masterkey';
Now we created the missing file 'security2.fdb' in the folder:
"/Library/Frameworks/Firebird.framework/Resources/English.lproj/var/"
(jro)
Entity Framework 4.1 Code First works great with SQLEXPRESS on localhost. However, I'm now ready to connect to a regular SQL 2008 server.
I created a new database "NewEfDatabase".
Then changed my "ApplicationServices" connectionString in Web.config to point to my new database with integrated security.
But then I get this error:
"CREATE DATABASE permission denied in database 'master'."
So...
a) What permissions does EF 4.1 CF need on said SQL server to do its work?
b) Can I setup an empty database on SQL 2008 for EF 4.1 CF, or do I have to let it do all that work for me? (I'm not sure my DBA would appreciate letting my EF app have rights to do anything outside a particular database)
Did you make sure to set your Database Initializer to null in your code:
Database.SetInitializer<MyDbContext>(null);
All built-in implementations if the initializer may try to drop or create a new database. The error you get indicate that EF tried to drop/create a database but hasn't the right to do so in your SQL Server instance. The line above is the only option to avoid this generally and is suited (I think even absolutely necessary) for live environments anyway where you don't want accidental deletion (due to model changes or something).
Setup a login for your application within SQL server. Give that user dbcreator permission (by right clicking on the login, go to server roles, and check the "dbcreator" checkbox)
Try not to used the windows-intergrated authorization, like what I replied in this post: EF Code First - {"CREATE DATABASE permission denied in database 'master'."}.
It worked for me.