EF Code First - creating database - Login failed for user - entity-framework

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.

Related

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.'

CREATE DATABASE permission denied in database 'master' (EF code-first)

I use code-first in my project and deploy on host but I get error
CREATE DATABASE permission denied in database 'master'.
This is my connection string:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-test-2012615153521;Integrated Security=False"
providerName="System.Data.SqlClient;User ID=test;Password=test"/>
I had the same problem. This what worked for me:
Go to SQL Server Management Studio and run it as Administrator.
Choose Security -> Then Logins
Choose the usernames or whatever users that will access your database under the Logins and Double Click it.
Give them a Server Roles that will give them credentials to create database. On my case, public was already checked so I checked dbcreator and sysadmin.
Run update-database again on Package Manager Console. Database should now successfully created.
Here is an image so that you can get the bigger picture, I blurred my credentials of course:
Be sure you have permission to create db.(as user2012810 mentioned.)
or
It seems that your code first use another (or default) connection string.
Have you set connection name on your context class?
public class YourContext : DbContext
{
public YourContext() : base("name=DefaultConnection")
{
}
public DbSet<aaaa> Aaaas { get; set; }
}
I got the same problem when trying to create a database using Code First(without database approach). The problem is that EF doesn't have enough permissions to create a database for you.
So I worked my way up using the Code First(using an existing database approach).
Steps :
Create a database in the Sql server management studio(preferably without tables).
Now back on visual studio, add a connection of the newly created database in the server explorer.
Now use the connection string of the database and add it in the app.config with a name like "Default Connection".
Now in the Context class, create a constructor for it and extend it from base class and pass the name of the connection string as a parameter.
Just like,
public class DummyContext : DbContext
{
public DummyContext() : base("name=DefaultConnection")
{
}
}
5.And now run your code and see the tables getting added to the database provided.
Run Visual Studio as Administrator, it worked for me
This error can also occur if you have multiple projects in the solution and the wrong one is set as the start-up project.
This matters because the connection string used by Update-Database comes from the start-up project, rather than the "Default project" selected in the package manager console.
(credits to masoud)
I have resolved this problem in my way.
Try connection string in this way:
<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" />
remember to set default db from master to MFC (in your case, aspnet-test-2012615153521).
Double check your connection string. When it points to non-existing database, EF tries to create tables in master database, and this error can occur.
In my case there was a typo in database name.
As the error suggests, the SQL login has no permission to create database. Permissions are granted when the login have the required roles. The role having permission to create, alter and drop database is dbCreator. Therefore it should be added to the login to solve the problem. It can be done on SQL Management Studio by right-clicking the user then go to Properties>Server Roles. I encountered the same error and resolved it by doing exactly that.
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.
Shut down SQL Server from ‘Services’
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
Open another cmd window (as administrator)
Open sqlcmd on that terminal with:
sqlcmd -S .\SQLEXPRESS
Now add the sysadmin role to your user:
sp_addsrvrolemember 'domain\user', 'sysadmin'
GO
Re-enable SQL Server from ‘Services’
Credit to:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/76fc84f9-437c-4e71-ba3d-3c9ae794a7c4/
Create the empty database manually.
Change the "Integrated Security" in connection string from "true" to
"false".
Be sure your user is sysadmin in your new database
Now I hope you can execute update-database successfully.
If you're running the site under IIS, you may need to set the Application Pool's Identity to an administrator.
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
run this on your master database
ALTER SERVER ROLE sysadmin ADD MEMBER your-user;
GO
I'm going to add what I've had to do, as it is an amalgamation of the above.
I'm using Code First, tried using 'create-database' but got the error in the title.
Closed and re-opened (as Admin this time) - command not recognised but 'update-database' was so used that. Same error.
Here are the steps I took to resolve it:
1) Opened SQL Server Management Studio and created a database "Videos"
2) Opened Server Explorer in VS2013 (under 'View') and connected to the database.
3) Right clicked on the connection -> properties, and grabbed the connection string.
4) In the web.config I added the connection string
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=MyMachine;Initial Catalog=Videos;Integrated Security=True" providerName="System.Data.SqlClient"
/>
</connectionStrings>
5) Where I set up the context, I need to reference DefaultConnection:
using System.Data.Entity;
namespace Videos.Models
{
public class VideoDb : DbContext
{
public VideoDb()
: base("name=DefaultConnection")
{
}
public DbSet<Video> Videos { get; set; }
}
}
6) In Package Manager console run 'update-database' to create the table(s).
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.
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 reason for this error may be originate from forwarding of version dependent localdb in visual sudio 2013 to the version independent localDB in VS 2015 onwards, so
simply change your web.config file connectionStrings from (localDb)\v11.0 to (localDB)\MSSQLLocalDB and it will certainly work.
and this is a good explaination for that Version independent local DB in Visual Studio 2015
If you are using .\SQLExpress as Data Source, you can add "User Instance=True" attribute to your connection string, to fix the error mentioned in the title.
For example,
Data Source=.\\SQLExpress;Integrated Security=true;
User Instance=true;
AttachDBFilename=|DataDirectory|\app_data\Northwind.mdf;
Initial Catalog=Northwind;
User instances allow users who are not administrators on their local computers to attach and connect to SQL Server Express databases. Each instance runs under the security context of the individual user, on a one-instance-per-user basis.
Reference: MSDN Link for SQL Server Express User Instances
This is so wrong - never over-elevate your permissions (use SA) where you don't need to do so.
To create database all you need is: CREATE DATABASE, CREATE ANY DATABASE, or ALTER ANY DATABASE permission as per
documentation or the login to be a member of the dbcreator
server level role.
Next - you need to make sure that mssql service login (NT Service\MSSQLServer by default) has permission to modify the file
system in the location where you want to create your database
(usually 1 .mdf file for data pages and 1 .ldf file for database
logs).
Then make sure you know where you create your databases! EF by
default sends the laziest query possible, defining only database
name: CREATE DATABASE [db_name] and then assuming all of the rest -
applying default settings. Make sure you either change these to reflect locations mssql engine service has access to or elevate
service permissions. Either way this modification requires mssql
restart tyo apply the setting.
Finally, make sure that you connect to the mssql using that login.
If you perform an EXECUTE AS USER statement to switch your login it
will fail. This method allows only to interpersonate DB user, not
the server level login. An attemp of doing it will give you CREATE DATABASE permission denied in database 'master' error message.
To get permission to create database in your local account follow the below given steps.
Disconnect from your local account.
Again Connect to Server with Login : sa and Password : pwd(pwd given to your local login).
Object Explorer -> Security -> Logins -> Right click on your server name -> Properties -> Server Roles -> sysadmin -> OK
Disconnect and connect to your local login and create database.
P.s: For me even without connect/disconnect to server, it worked!
I had the same issue, I tried couple of other methods, but none of them worked. I just simply exit the SSMS and run it as an administrator and it worked perfectly.
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..
Permission denied is a security so you need to add a "User" permission..
Right click you database(which is .mdf file) and then properties
Go to security tab
Click Continue button
Click Add button
Click Advance button
Another window will show, then you click the "Find Now" button on the right side.
On the fields below, go to the bottom most and click the "Users". Click OK.
Click the permission "Users" that you have been created, then Check the full control checkbox.
There you go. You have now permission to your database.
Note: The connection-string in the above questions is using SQL-server authentication. So, Before taking the above step, You have to login using windows-authentication first, and then you have to give permission to the user who is using sql-server authentication. Permission like "dbcreator".
if you login with SQL server authentication and trying to give permission to the user you logged in. it shows, permission denied error.

Why does Entity give me an "SSDL fragment is required" statement with a remote DB, but not SQL Express?

Similar to this question, I am trying to run an Entity CodeFirst project. I'm using the CreateDatabaseIfNotExists initializer. I am a sysadmin on the box the connect string points to.
If I change (or remove) the connection string, Entity will create the database on my local SQLExpress instance. Why won't it create the database on my remote instance? And, furthermore, why does it seem to require an artifact of data-first? This is a brand new project that is using nothing but code-first.
Using EF4.2. Remote machine is SQL2k8.

EF 4.1 CF: CREATE DATABASE permission denied in database 'master'

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.

Can't recreate SQL Server Express database with Entity Framework Code First and MVC 3 without changing the database name

When I run the application with the following connection string the database file is created successfully.
<add name="ConnString1"
connectionString="Data Source=.\SQLEXPRESS;
Database=Database1;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
If I delete the database file and try to run the application again the database file fails to be created and I get the following inner exceptions:
The underlying provider failed on Open.
{"Cannot open database \"Database1\" requested by the login. The login failed.\Database1\nLogin failed for user 'computer\\someuser'."}
If I change Database=Database1 to Database=Database2 in the connection string then the database file is created successfully. The problem repeats itself always.
How can I recreate the database file without having to change the database name?
Check to make sure the directory rights allow you to delete the mdf file and the the login has drop schema/table privileges directory rights are a common issue with mdf files due the high security placed on these files due to their potentially sensitive nature
I can see this is an older post - hopefully this can help someone in the same predicament.
Using code first, the first time the application runs it builds the db no problems - it knows it doesn't exist because it hasn't previously built it. Code first also takes a hash value of the models used and stores that in the new database - check for a table called EdmMetadata - thats where the hash value is stored. It uses the hash value to subsequently check if the model has changed from build to build, so it knows whether to drop the database and rebuild.
The second time through after you've deleted the database, it looks for the missing database to compare the model hash value, and can't find it because the database is now missing.
My workaround is to add a meaningless field (remembering to delete it after development) to one of the models to force the rebuild, without deleting the database. Alternatively, you could just modify the db hash value to force the rebuild.
This works with the code first application databases - not so sure with the membership database.