entity framework 4.1 code first CREATE DATABASE permission denied in database 'master' - entity-framework

I have created a generic repository project using Entity Framework 4.1 and it works great with my projects when added as an existing project to them but it doesn't work on them when just referenced as dll.
I get this error
CREATE DATABASE permission denied in database 'master'.
but I have added app.config file and set relevant connection string to my SQL Server 2005 database (I have used DbContext as type my context)
Please help me.
Here is my connection string :
<configuration>
<connectionStrings>
<add name="TasksEntities"
connectionString="server=(local); database=Tasks; trusted_connection=false; User=sa; Password=****; Persist Security Info=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

I just ran into this myself. The connection string name must match the class name of your DbContext subclass exactly. If it doesn't EF will not find the connection string and will try and fall back to doing something else (SQL embedded?) which doesn't work on my machine (I have full SQL Server installed).

You must verify where is configured your connectionstring if you are working with more than one project for example. If your startup project in your solution has a connectionstring configured and in Package Manager Console is pointing to the project with EF Migrations configured as well (in "Default Project").
You can run with the command in Package Manager Update-Database -Verbose what is the startup project and source migration or specify putting the parameters in the command:
Update-Database -SourceMigration MvProject.Data -StartUpProjectName MyProject.Web -Verbose

Seems like your credentials in the connection string should have permission to create database on your server. Log in to your database server and check whether your user account has the correct permissions. This will be a http://www.sqlservercurry.com/2008/04/resolving-create-database-permission.html

Related

Entity Framework auto generate database to SQL Server Compact

I am using VS 2012 and the model first approach in Entity Framework 6 to generate a database in SQL Server Compact 4.0. I have installed the Entity Framework package from NuGet and have added EntityFramework.SqlServer.Compact to my references. Once I build my model I try to generate the database with the "Generate database from model..." instruction. I can go through the Generate Database Wizard without any problems.
When I run update-database in the Package Manger Console I get
No migrations configuration type was found in the assembly
Fixing this error I used Enable-Migrations which gave me a new error
Creating a DbModelBuilder or writing the EDMX from a DbContext created using Database First or Model First is not supported. EDMX can only be obtained from a Code First DbContext created without using an existing DbCompiledModel.
The connection string that was generated is below
<connectionStrings>
<add name="Model1Container"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="data source=C:\Users\RSargent\Desktop\CompactDatabase\MyDatabase1.sdf""
providerName="System.Data.EntityClient" />
</connectionStrings>
I have tried using |DataDirectory| for the connection string path but this doesn't work for me as all I get is a few errors:
Missing required whitespace
<connectionStrings>
<add name="Model1Container"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\MyDatabase1.sdf""
providerName="System.Data.EntityClient"/>
</connectionStrings>
From the research I have done usually the connection string is the problem in these situations. Am I setting up the connection string correctly? Or does anyone know of another reason why I can't auto-generate a database?

EF6 migrations (LocalDb) update-database login failed

VS 2013 MVC5 code first project.
I’m working through the ASP.NET Getting Started with EF6 using MVC5 tutorial to get up to speed on the latest changes and I’m having a problem with migrations.
In the first module the database is created using a database initializer:
<contexts>
<context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
<databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
</context>
</contexts>
and this connection string:
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
This works fine. In the Code First Migrations and Deployment module migrations are setup. The initializer is commented out and the name of the DB is changed to ContosoUniversity2:
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
When update-database is then run from the Packager Manager Console it fails with the error message:
Cannot open database "ContosoUniversity2" requested by the login. The login failed.
Login failed for user 'MyMachine\MyUser'.
I’ve re-run both scenarios several times with the same user and the same results. If I change Initial Catalog to AttachDbFilename=|DataDirectory|\ContosoUniversity2; update-database succeeds (the DB is now in the App-Data folder of the project rather the root of the users profile):
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0; AttachDbFilename=|DataDirectory|\ContosoUniversity2;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
You have to use Initial Catalog when deploying though. The production connectionString is set separately in the Web.Release.Config so that is workable.
The question is why the need for the fix, why doesn’t Initial Catalog work with update-database on the development side?
Update 1:
The problem is not with migrations but with LocalDb
MyUser has full rights in SQLExpress (sysadmin). I can log into SSMS under MyUser and fully manage DBs. I ran several tests. Even though I created the initial DB for the tutorial as MyUser it now throws the login failed error if I rebuild the app from scratch and use databaseInitialzer. If I run VS under Admin both databaseInitialzer and update-database work without any problem. If I then copy the DBs from the Admin's user profile root to MyUser's and then run VS, not as Admin, while logged on as MyUser both the databaseInitialzer and update-database then work if the DB is prior existing.
If I change the connectionString to AttachDbFileName and run either databaseInitialzer and update-database MyUser can create a DB in the App_Data folder proving MyUser has DB create rights. MyUser obviously has full rights to the root of its own user profile. There is something amisss with the LocalDb implementation.
Does any one have any insight on this question?
If you delete the DB file, it still stays registered with SqlLocalDB. If LocalDb gets hung up with can’t attach (after manually deleting the DB file) or Login failed see JSobell’s and CodingwithSpike’s answers here:
ef5-cannot-attach-the-file-0-as-database-1.
Run ‘sqllocaldb.exe stop v11.0’ and ‘sqllocaldb.exe delete v11.0’ from the PM Console
UPDATE:
Easier yet use SSMS. Server name: (local)\v11.0, Windows Authentication. This is really the best way to manage your localdb databases.
I'm working with VS 2013 and EF6.1 .
I got similar kind of error when I work with migration and delete database.
I was unable to recreate database again.
Found that error due to SQLExpress local database instance is running on background and keeping the deleted database connection with it.
following are the steps to handle this situation.
Delete the database files (.mdf and .ldf) files.
Delete Migration Folder from your application.
Delete any database connection to that database from server Explorer data connections.
Go to windows Command Prompt (IF VS 2012 or earlier you have to use the VS Command prompt).
Run "sqllocaldb.exe stop v11.0" (This will stop the v11.0 service)
Run "sqllocaldb.exe delete v11.0" (This will delete the v11.0 service)
Go to Package Manager Console in Visual studio.
Run "Enable-Migrations" (This will create Migration folder and content)
Run "Add-Migration init" (This will scaffold the changes to next migration)
Run "Update-Database" (This will create the database again)
I change Standard Security to Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
in appsetting.json you can write this code
`{
"ConnectionStrings": {
"onlineStoreDB": "Server=.;Database=onlineStore;Trusted_Connection=True"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}`
It worked for me.
Exchange from connection string
Data Source=(LocalDb)\v11.0;
to
Server=.\SQLExpress;
This helped me for Code First technique during migration
This will fix your problem and you can update and add as many methods and properties to the Model as you want
Notes: Step 1{If you initiated your databse as in the tutorial}
From the PM Console:
Enable-Migrations -ContextTypeName ContosoUniversity.DAL.SchoolContext
add-migration Initial
update-database
I'm kind of late but I have encountered the same issue while doing Getting Started with EF6 using MVC5.
The issue appears due to an invalid Database Initialisation in the example.
Change
public class SchoolInitializer : System.Data.Entity. DropCreateDatabaseIfModelChanges<SchoolContext>
to
public class SchoolInitializer : CreateDatabaseIfNotExists<SchoolContext>
and it will create the database with no issues.
Initialisation method that is used in the example does not create a new database by default. Not sure if it is a bug or not.
'PM> enable-migrations
Enable-Migrations is obsolete. Use Add-Migration to start using Migrations.'

How to create a localDb with mdf file inside the project directory?

I tried to get started with LocalDb and got few problem. I created a new LocalDb using EF Generate Database Wizard and if I created a new database, it saved the mdf file inside user profile. If I manually created mdf and chosed 'Attach a database file' option, edmx.sql cannot be executed. I would like to have my localdb inside the project directory and everything else (EF, .Net membership identity) still be working fine.
I have also tried putting AttachDbFilename=MyDataFile.mdf to the connecting string but when i run edmx.sql, i got an error saying mdf cannot be found. It is still searching in user profile directory.
I don't have SSMS installed on my machine. I am using VS2013 Pro.
Updated:
<add name="DeveloperNetworkContainer" connectionString="metadata=res://*/DeveloperNetwork.csdl|res://*/DeveloperNetwork.ssdl|res://*/DeveloperNetwork.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\v11.0;AttachDbFilename=|DataDirectory|\DeveloperNetworkDb.mdf;initial catalog=DeveloperNetworkDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
.
SET QUOTED_IDENTIFIER OFF;
GO
USE [DeveloperNetworkDb];
GO
IF SCHEMA_ID(N'dbo') IS NULL EXECUTE(N'CREATE SCHEMA [dbo]');
GO

How to roll back EF migration on Azure

HELP! I have an MVC4 app hosted on Azure. I'm using EF code-first. Here's my scenario:
I set a flag in my production database to cause the website to display a "website is disabled" message in lieu of the usual website behavior.
I published an update to the website code to the Staging instance. When I ran the staging instance, it applied some migrations to the database schema. At this point, the production instance would not work if I were to re-enable it because the database schema is not compatible with the production code
When I tested the staging instance, I discovered that it doesn't work correctly.
Now I realize that I don't know how to back out the EF migrations that I applied so that I can re-enable the Production instance and get back to where I was before I ran the Staging instance. I know how to use the Package Manager Console in Visual Studio to go to a specific migration in the local database, but I have no idea how to manually tell Azure to update-database to a specific migration.
Navigate to your database's dashboard on the Azure portal and select "Show connection strings". Copy the ADO.NET string into the -ConnectionString switch of the Update-Database command. You should end up with something like this:
Update-Database
-TargetMigration {YourMigration}
-ConnectionString "Server=tcp:{your server name}.database.windows.net,1433;
Database={your db};
User ID={your user}#{your server};
Password={your password};
Trusted_Connection=False;
Encrypt=True;
Connection Timeout=30;"
-ConnectionProviderName "System.Data.SqlClient"
Run a "Get-Migrations"
it will display a list of migrations.
After that:
Update-Database -TargetMigration:"{NAME_OF_SELECTED_MIGRATION}"
where {NAME_OF_SELECTED_MIGRATION} will be replaced with the name you want.
PS: remove "{" and "}" characters.

EF Code First - creating database - Login failed for user

I originally had a EF code first set up that was connecting to an existing database. This was working fine.
I then made a couple changes to a POCO and decided to have code first generate the new database for me.
Getting error: Cannot open database \"MyDatabase\" requested by the login. The login failed.\r\nLogin failed for user 'DOMAIN\username'.
I deleted the old database, but I did not change the connection string:
<add name="MyDatabaseContext" connectionString="Data Source=localhost;Initial Catalog=MyDatabase;Integrated Security=True;" providerName="System.Data.SqlClient" />
I have a sql server 2008 instance on my local machine and my domain username is in "sysadmin" role.
I tried various Database initializers and I get the same error for all. It is failing on the first query call, but code first does not create the database. I can point the connection string to a copy of the old database (before changes) and it will run fine, except that it is my old schema even though I specified the DropCreateDatabaseAlways initializer. This is not making sense, and not following what I experienced on my home machine working with code first.
Using Visual studio 2012 and EF5.
I need to be able to have code first generate a new database. What is going on?
Found out I had a static constructor in my DbContext class, which was overriding the database initializer.
static MyDbContext()
{
Database.SetInitializer<MyDbContext>(null);
}
Code first reverse engineer will put this in so you don't overwrite your existing database. When I switched I wasn't thinking about it.
Hope this will help someone else out.