EF 6 Code First : "CREATE DATABASE permission denied in database 'master'." on existing database - sql-server

I'm facing some troubles with my EF Model.
History: When my app was released in production a few years ago, my EF model was created via the Model First (edmx) technique. I works well on my production server with my SQL SERVER db.
Now I'm doing some improvements on my app, and I decided to leave the Model First technique to go on the Code first technique. It's working great on my localhost, but when I release my new app version on my production server and when my app tries to use the model I got this message:
CREATE DATABASE permission denied in database 'master'.
But I don't get it... My database still exists on my production server (since several years). Why does EF would like to create something? What can be wrong?
Thanks in advance for your answers.
EDIT:
Summary:
For the same database on the same server
For the same connectionstring
For the same EF version (6)
App with Model First works without problem
App with Code First throw exception CREATE DATABASE permission denied in database 'master'.
BUT the database already exists. Why this error? Why does the code first version tries to create a database?

Check this
https://stackoverflow.com/a/19198471/8186328
Be sure that your connection string name is the same that the base constructor of your dbContext

Related

Recreate database when running ASP.NET Core Web API on another server

I have a project that is an ASP.NET Core Web API using Entity Framework Core.
A few time ago I created the database using code-first approach with the necessary migrations.
Now I want run the project in other machine and I get the error when I try for example an post to one endpoint:
Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open database "MyDatabase" requested by the login. The login failed.
However I think the problem (and I checked with ssms) is that the database doesn't exist.
My connection string, in DbContext is:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Server=(localdb)\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
What is the best way to recreate the database on this machine?
Thanks
Remove
;Database=MyDatabase
From the connection string.
Then you can create the dtaabase
CREATE DaTABASE MyDatabase
After the command has run
USE MyDatabase
so that you can create tables and run sql commands on it.
This will wrk on any database.
You should check prior to the creation if the database exists, bu that is highly depending on the rdms that you are using

SQL Server connection failing with LinqToSQL but working with EF 6

I have an application (.NET WPF LinqtoSQL) that works when I connect to a local database. When I changed to a database on a different server I get an error (SQL Server Instance not found error 26).
The solutions to this error are all based on the server, firewall, and making sure SQL Server Browser is up and running, none of which I can do because I have no rights on the server.
But I created a small test application using WPF and EF (ADO.NET) that successfully connects to the exact same database (and table). I have no clue what might be going on, but I am not sure I want to re-write the application using EF (at least right now).
Does anyone understand the difference between the framesworks' connection method to point me to a possible solution for the LinqToSQL version beyond waiting for the IT guys to "fix" the server?
Given the revelation above that EF and L2S use the same connection class I figured a new project that points to the new server would fix my issue. And it did:
I created a new project, added a new L2S item, and then copied in all of my old projects views/ viewmodels/ etc. and it runs just fine.
I thought I could simply update the connection string, as this is what I believe I have done successfully in the past, but perhaps there is something else had to be set somewhere in the project settings or generated DataContext code to the new server. If anyone knows what that is please answer and I'll accept it.

Asp.NET MVC 4 deployment issues related to LocalDb and SQLExpress

I am trying to deploy a Asp.NET MVC 4 app to a third-party host, and encountered some problems while following this tutorial.
The tutorial created 2 New SQL Server Database, and set the Remote connection string of DefaultConnection to one SQLExpress database and that of SchoolContext to another. However, I want to have only one database, so I only created one New SQL Server Database, and used the same connection string for DefaultConnection AND MyAppContext. Would this cause problem?
Right now my app won't publish with the following error. not sure if it stems from this. MyAppUsr comes from a Grant script, Grant.sql, that I developed from this tutorial.
Error 3 Web deployment task failed. (An error occurred during execution of the database script. The error occurred between the following lines of the script: "8" and "11". The verbose log might have more information about the error. The command started with the following:
"CREATE USER [MyAppUsr] "
The login already has an account under a different user name. http://go.microsoft.com/fwlink/?LinkId=178587 Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_SQL_EXECUTION_FAILURE.) 0 0 MvcCP
MyAppContext uses LocalDb instead of SQLExpress. The deployment in the tutorial uses SQLExpress. Can I just create a new SQLExpress database and have MyAppContext (LocalDb) "points to" the SQLExpress database?
You must have run the script at least once prior, correct? Because what it is saying is that the user [MyAppUsr] already exists. You will need to drop the user first, then rerun it. ie:
DROP USER [MyAppUsr]
You can embed that into your script, better yet, put a conditional check if exists...

Foreign Key constraint error when performing fresh install of Piranha CMS

Piranha CMS is a programmer oriented CMS (I prefer to write it since I've been downvoted last time!). I've spent all the afternoon trying to fix this problem : Whether I try to migrate from a Sql Compact Server Database to a SQL Server Database, or to start everything from scratch with an empty SQL Server Database, I get the following error :
Introducing FOREIGN KEY constraint 'FK_dbo.category_dbo.sysuser_category_updated_by' on table 'category' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I am able to pass the first step (admin account and password creation), but this exception is thrown whenever I try to log in.
What am I doing wrong ?
Thanks for your help !
UPDATE
The stack indicates where the error is coming from :
[HttpException (0x80004005): The pre-application start initialization method
Start on type Piranha.Web.ApplicationModule threw an exception with the following
error message: Introducing FOREIGN KEY constraint
'FK_dbo.category_dbo.sysuser_category_updated_by' on table 'category'
may cause cycles or multiple cascade paths. Specify ON
DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9915300
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr,
HttpContext context) +254
There seem to be a problem with the Method Start of Piranha.Web.ApplicationModule.
Also I have noticed the configuration of Entity Framework is :
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
I wonder about the :
invariantName="System.Data.SqlClient
Since System.Data.SqlClient is the Provider mentionned in my connection string. But I don't know if it's relevant since it may just mean that EF is used to retrieve the data. But I wonder if there might not be a conflict since both your internal scripts and EF use this connection string with this provider that is mentionned. Also, I'm not sure, but I know that with code-first EF also creates meta-data when it creates a database. Perhaps since your internal scripts doesn't create them, EF considers that the DB doesn't exist ?
Update 2
I have some news, I have added
Database.SetInitializer<Piranha.DataContext>(null);
In Application_Start to avoid Database recreation. It seems to have solved the database re-creation problem. I no longer see the exception concerning the constraint. However now the PageController throws a null reference exception after trying to log in, and I still can't see anypage of the public website (The publc site throws an internal server error). My guess is that when I set the Initializer to null, it also prevents EF from populating the DB with the basic data of the Framework. That's a good step further, so it seems that the problem comes from the Piranha DataContext Configuration.
Update 3
Just to give more details :
When trying to log in, I'm redirected to manager/page which throws a null reference exception as I said before. This exception is thrown when I try to access most of the pages of the manager (I have tried template/pagelist, setting/userlist) however, when I try "manager/post" I get the following error :
Invalid object name 'dbo.post'.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.post'.
But the 'post' Table do exist in the Database... It's a fresh install, I only changed two things : the connection string, and the Database Initializer code I added in Global Asax.
As far as i can see, in version 2.2.0 there is not a constraint for table "category" with the name "FK_dbo.category_dbo.sysuser_category_updated_by". I guess something went wrong installing a fresh version.
If you have access to SQL server with a management tool (like 'SQLServer Management Studio'), try to run to following query against your Piranha-database:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='category' AND CONSTRAINT_TYPE='FOREIGN KEY'
You should see three constraints, none of them with the word 'sysuser' in its name.
You might want to try a fresh install again, following the instructions here:
http://piranhacms.org/docs/introduction/getting-started
Before you proceed with the web installer, you should create a clean empty database using SQL Server Management Studio. You can run these SQL-commands in the Management Studio:
-- create new user
CREATE LOGIN piranha2 WITH PASSWORD = 'piranha2'
GO
-- create new empty database
CREATE DATABASE piranha2
GO
-- select new database
USE piranha2
GO
-- assign user to database
CREATE USER piranha2 FOR LOGIN piranha2
GO
-- add role to user
EXEC sp_addrolemember 'db_owner', 'piranha2'
GO
After that, open Web.config, look for section "connectionStrings". You should see a couple of lines. Add a new line in this section with this content (don't forget to use your own servername or ip-address after "server="):
<add name="piranha" connectionString="server=192.168.1.1;database=piranha2;user id=piranha2;password=piranha2;multipleactiveresultsets=true;" providerName="System.Data.SqlClient" />
Start the installer. It should find your database and create tables and constraints.
Hope that will help.
The error message you're providing is a typical Entity Framework error when trying to create a DbContext in the database. The only problem is that Entity Framework is not responsible for creating the tables in Piranha CMS, this is done by internal SqlScripts embedded in the framework dll.
If the tables are created successfully in the database and you still get this error when trying to log in, my only guess is that Entity Framework is for some reason using an incorrect Connection String trying to create the database somewhere else. Although I'm puzzled how this could happen through misconfiguration.
Can you access the public site after install?
UPDATE
I've created a new Blank MVC Application, installed PiranhaCMSMvc into it, installed the database and logged into the manager without problems. I've pushed the blank project to this repo:
https://github.com/tidyui/Blank
Download this source code and see if it works for you after you've modified the connection string. If it works, try to compare the projects to see what is causing your error. If it doesn't work then there's something else wrong with your setup that is conflicting somehow. Keep me updated!
Regards
Reason for error is Schema name in my case.
Solution:
You require to have database objects belonging to dbo schema, if you've installed on fresh database with different schema name, it will throw this error. To fix it, change schema name of those tables to dbo and it will work like a charm.
Well, I spent 2 days on it so I had no choice but to change CMS. I'm running late because of this problem. Fortunately I only had created a couple of pages. I'm currently moving to Umbraco. I've played with it this afternoon and it's actually less complicated than what I heard so it should do the trick. It's also perfectly working on my production server.
However, I still have an other project that I would like to keep on Piranha CMS. Since I've planned to move it from Compact SQL to SQL Server too, I'm really concerned with this issue.
I cannot add a comment yet, so have to give a second answer:
My previous answer didn't make sense so i have to make something up with you.
If you still want to investigate some time:
to re-produce your problem i've created a VHD with Windows 7 Pro-N (un-activated), MS SQL 2012 Express and VS 2013 Express Web. You can run this as virtual machine either under Windows 7 Virtual PC or Windows 8 Hyper-V. With the Blank project of Hakan I was not able to reproduce your problem. However, if you manage to re-produce your problem in this virtual machine, you can share the VHD with Hakan so he can take a look what is happening (of course if he's willing to do so).
Also, what i'm wondering: if you rename the affected table or drop it, is the error-message moving to another table and/or constraint? Of course it is not a solution to drop the table, but it might tell more about what is going on.

Database is not created after publishing on Windows Azure

Actually, I'm working on a basic ERP for a very small business. I'm using ASP.Net MVC 4 Code First and I use Windows Azure as web hoster. All is working fine on my local computer, and deployement is done without issues : website is reachable. However, my application crash whenever a database access is required, with a "very descriptive" error : "Error. An error occurred while processing the request.". There are no clue or detailled error in logs file about this error.
After digging during two days, I've understood that my database is not initialized : all tables are created, but columns aren't set. Because tables are created, I doubt it's a connection string error, but a migrations one. All tries (though Initializer class) I have done to force a database reinitialisation failed.
I searched a while on the Internet, but I saw no one having the same issue than me.
Is trhere someone who have already encoutered this case, and is there a solution to fix it ? Thanks for your answers.
PS: Sorry for english mistakes, it's not my mothertongue :)
If the database you are using is sql than you should use
SQL Database Migration Wizard for deploying on-premises sql database to windows azure. This will do the job perfectly and effortlessly.

Resources