asp mvc 3 noobie: CREATE DATABASE permission denied in database 'master' - sql-server

I'm an asp mvc 3 noobie. I've done a few tutorials and am now ready to keep learning by trying to build a site.
In all the tutorials, you connect to a SQL CE or SQL Express DB. But I want my site to build a DB on sql server.
I created a database on my networked server that I'll call MyDB. Then I set my connection string in my web config file like this:
add name="ApplicationServices"
connectionString="Data Source=Server\ServerInstance;Initial Catalog=MyDB;Integrated Security=True"
providerName="System.Data.SqlClient"
I created models and a scaffolding controller.
I created a simple DataBaseContext like this:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
But when I hit the following line in the scaffolding controller, i get the error:
Function Index() As ViewResult
Return View(db.Employee.ToList()) //CREATE DATABASE permission denied in database 'master'`.
End Function
Should I fix this by changing the permissions on the MyDB database? Is this a permissions issue on the SQL server side? I am confused why I am getting a Create database error because the DB already exists.
Am I getting this error b/c I have already created the database? Does the scaffolding want to create the database somehow?

Sounds like it is trying to create a new DB by the error message. I'm guessing that you are using EF code first with your project and using it's migration capability to build your DB. Check the setup of the EF context to make sure it's using your connection string.
The connection string or its name can be passed to constructor of DbContext. If you are using default constructor it searches for the connection string with the same name as the name of your derived context class. Basically, make sure your connection string has the same name as your derived dbcontext class and it should find it.
See this post for additional information

1.You need to set IIS app pool identity to be ASP.NET integration mode.
2.Add a login in SQL Server for IIS APPPOOL\ASP.NET.
3.In SQL Server, set IIS APP POOL login to have dbcreator role.

USE master;
EXECUTE sp_addsrvrolemember #loginame = N'YourAppUserLogin', #rolename = N'dbcreator';

<add name="Default" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=test2;user id=sa;password=123456"
providerName="System.Data.SqlClient" />
Use this connection string for your application

Related

CRUD using angularJS and webAPI

I am trying to perform CRUD using angularJS and webAPI using EF database first approach but I got blank page when i ran project, i even found issue but dont know how to solve it..
issue is realted to database connectivity..
I have following method for listing in my api controller,
[ActionName("get"), HttpGet]
public IEnumerable<Person> Persons()
{
return db.Persons.ToList();
}
when i put debugger and debug this method i Got = base = {"This operation requires a connection to the 'master' database. Unable to create a connection to the 'master' database because the original database connection has been opened and credentials have been removed from the connection string. Supply an unopened..." and further "childrens can not be evaluated" error.
here is my connection string :
<connectionStrings>
<add name="PersonDbContext" connectionString="Data Source=PCA74\SQLEXPRESS;Initial Catalog=Practice:User ID=sa;Password=db123#" providerName="System.Data.SqlClient"/>
any ideas?

Code-first MVC 4 using Entity Framework and SQL Server 2012

This question is not about SQL Server "3xpr355" (the obfuscation
in quotes is by design; it should prevent future searches from hitting
dead-ends, as mine have done).
I am using code-first and Entity Framework to develop an MVC 4 application. The SQL Server, IIS, and Visual Studio are all running on the same machine.
I was originally using SQL Server "3xpr355" but the requirement to put it on an exposed-to-the-Internet-via-ISS machine made hooking it up to a full-featured SQL Server necessary. I have the application set up to drop and re-create the database whenever the models change:
public class XyzDBContext : DbContext
{
public XyzDBContext()
: base("XyzDBContext")
{
Database.SetInitializer<XyzDBContext>(new DropCreateDatabaseIfModelChanges<XyzDBContext>());
}
public DbSet<XyzModel> XyzModels{ get; set; }
}
Here are my connection strings:
<connectionStrings>
<add
name="DefaultConnection"
connectionString="Data Source=.;Initial Catalog=aspnet-Xyz-20150131102119;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
<add
name="XyzDBContext"
connectionString="Data Source=.;Initial Catalog=XyzDatabase;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Expectations:
Execution of the portions of the application that use XyzDBContext should cause the database "XyzDatabase" to be created (if necessary).
Execution of the portions of the application that use the Membership Provider should cause the database "aspnet-Xyz-20150131102119" to be created (if necessary).
Actual Results:
Exception is thrown: System.Data.ProviderIncompatibleException "An
error occurred while getting provider information from the database.
This can be caused by Entity Framework using an incorrect connection
string. Check the inner exceptions for details and ensure that the
connection string is correct."
Inner Exception:
System.Data.ProviderIncompatibleException "The provider did not
return a ProviderManifestToken string."
Inner Exception:
System.Data.SqlClient.SqlException "Login failed for user
'DOMAIN\SERVER$'."
Measures:
I have tried using SQL Server Management Studio to add a login for the "DOMAIN\SERVER$" user, but the login always fails.
I have researched and tried many permutations of the connection strings, all but a few of the examples I have found were for use with SQL Server "3xpr355".
Well if you map each connection string (database) to it's own DbContext the you could reach your expectations but you still have to work with two contexts (which is painful).
Your third actual result is due to IIS that can't connect to the database. You have to go to IIS manager and change the identity of the application pool under which your application runs (You can change it to LocalSystem)
Finally, try this if you have already the databases created:
public class DefaultConnectionContext : DbContext, IDisposable
{
public DefaultConnectionContext()
: base("name=DefaultConnection")
{
Database.SetInitializer<DefaultConnectionContext>(null);
}
// Some dbsets
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
public class XyzDBContext : DbContext, IDisposable
{
public XyzDBContext()
: base("name=XyzDBContext")
{
Database.SetInitializer<XyzDBContext>(null);
}
// Some dbsets
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Hope That helps
The solution to this problem is multifaceted:
Create an Application Pool
In IIS Manager, visit the "Application Pools" node and select the "Add Application Pool..." Action:
Select the new Application Pool and select the "Advanced Settings..." Action, then select the "..." button (on the "Identity" field):
Set the Application Pool identity to "LocalSystem"
Grant Permission
In SQL Server Management Studio (when connected to the database service), visit the "NT AUTHORITY\SYSTEM" node under "Logins" and bring up the "Properties" view, then select the "Server Roles" page, and grant all of the privileges by selecting the check-boxes:
In IIS Manager, Right-click on your site and select "Manage Application/Advanced Settings..." and Set the "Application Pool" property value to "CodeFirstMVC".
Run the Application
Run the application and visit the areas that would require a new database to be created; you should now see a new database on your SQL Server instance.

Parallels Plesk Panel connecting to database server connection string

I am using Entity Framework to access the data from my database. It's an MVC application and works fine locally. When I deploy the application on hosting (Parallels Plesk Panel, MS hosting) I get problems with accessing the SQL server instance. There are options in the cPanel which hold connection strings.
LocalSqlServer:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
xContainer:metadata=res:///Models.x.csdl|res:///Models.x.ssdl|res://*/Models.x.msl;provider=System.Data.SqlClient;provider connection string=
When I upload the site xContainer is generated alone. I found the sql server's instance name and applied it to the data source. In my web.config file I am using the the xContainer. The code after this paragraph is what it seems logic to me to add after the connection string= in the xContainer.
I have tried this with various properties. Data source, initial catalog, and the other info are filled into the conn string (here I am showing only /).
Data Source=x;Initial Catalog=/;Persist Security Info=True;User ID=/;Password=/;MultipleActiveResultSets=True providerName=
The error I receive is that the sql server instance cannot be found. If I add the last piece of code to the container it tells that I don't have a providerName, After adding a providerName the string is deleted to the starting xContainer string:
metadata=res:///Models.x.csdl|res:///Models.x.ssdl|res://*/Models.x.msl;provider=System.Data.SqlClient;provider connection string=
The error I receive is that the **sql server instance cannot be found**.
So, what is the SQL instance name? :)
it maybe not ".\SQLEXPRESS" but ".\SQLEXPRESS2012" or even ".\MSSQLSERVER" or anything else.
You will need to Edit the Web.Config file manually. The ASP.NET Settings page will remove the providerName.
An example of a connection string using EntityClient is below. You can remove the metadata information if you're not using an Entity Model. You will notice the providerName is outside of the actual connectionString and is the reason you will need to edit the file manually.
connectionString="metadata=ModelInformation;provider=System.Data.SqlClient;provider connection string="data source=IP;initial catalog=DATABASE;User ID=USERNAME;Password=PASSWORD;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"

ASP.NET membership using SQL Server

I am trying to create an MVC 3 app using asp.net membership in a sql server database. I want to be able to use the Entity Framework for development on this app.
I have created by database and used the aspnet_regsql utility to add the membership tables to the database. The part I'm stuck on is how to connect to this database using my application.
I have added an entity model to the project which generated a new connection string in the web.config and I have tried changing the connectionStringName property on all the membership related entries to the new string like so:
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="BlogV1Entities" applicationName="/" />
but this is not working as I am getting errors when trying to create a user through the app or ASP.NET Configuration utility
An error occurred while attempting to initialize a System.Data.SqlClient.SqlConnection object. The value that was provided for the connection string may be wrong, or it may contain an invalid syntax. Parameter name: connectionString
Can anyone point me in the right direction to properly get this setup so my app can access the database?
EDIT: In response to first comment this is what the connection string looks like this:
connectionString="metadata=res://*/BlogV1Model.csdl|res://*/BlogV1Model.ssdl|res://*/BlogV1Model.msl;provider=System.Data.SqlClient;provider connection string="data source=jesse-laptop;initial catalog=BlogV1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
the entity framework connection string won't work when using asp.net membership. I have dont in my project like this;
i-e You need separate connection string for that;
your membership connection string;
<add name="DAConnection" connectionString="Data Source=.\sqlexpress;initial catalog=E:\MYWORK\DIGITALASSETSMVC3\DAMVC3\APP_DATA\DAMVC3.MDF;integrated security=True" providerName="Syste.Data.SqlClient" />
you entity framework connection string;
<add name="DAEntities" connectionString="metadata=res://*/Models.DAModel.csdl|res://*/Models.DAModel.ssdl|res://*/Models.DAModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=E:\MYWORK\DIGITALASSETSMVC3\DAMVC3\APP_DATA\DAMVC3.MDF;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
It's not a valid connection string which can be used by Membership, it's kind of special connection string just can be used by EF (because of different provideName which Membership expect AFAIK).
Add a clear regular connection string and reference to it instead.

External SQL Server access in MVC 3 + Entity Framework for query-only

I'm devoloping a system using MVC 3 with EF 4. In this system, I need to lookup some information that already exists in an external database.
Saving me project's information on my database is OK. I defined my Models on it and let DbContext create the tables on my server.
The problem is when I try to query some data from the external database. I've added the connection string in the properly place on Web.config:
<connectionStrings>
<add name="ExtDBConnectionString" connectionString="Data Source=path.to.server;Initial Catalog=DBName;Persist Security Info=True;User ID=user;Password=pass;Pooling=True;Min Pool Size=5;Max Pool Size=60;Connect Timeout=2;" providerName="System.Data.SqlClient" />
</connectionStrings>
Is it possible to just create some queries to this server on my project without the overload of recreating all the Models from this external database? I know I can recover this connection string on my code by using the command System.Configuration.ConfigurationManager.ConnectionStrings["ExtDBConnectionString"].ConnectionString, but how can I create a connection and instantiate my queries?
Thanks in advance!
Edit: #rouen called my atention I didn't explicitly said the databases are differents. They do not share the same schema! The external database is the output of a report; so, I need to traverse it on my project to import the relevant lines to the local database.
I would just use standard ADO.NET. Use the SqlConnection and SqlCommand classes.
ADO.NET Examples on MSDN:
http://msdn.microsoft.com/en-us/library/dw70f090.aspx
Is the remote database schemantically identical as your local ? If yes, you can pass connectionstring to constructor of ObjectContext/DbContext, and it will use that database.
http://msdn.microsoft.com/en-us/library/gg679467%28v=vs.103%29.aspx

Resources