Connection string not working in ASP.NET Core - asp.net-mvc

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb; Database=ABC; Trusted_Connection=True; MultipleActiveResultSets=true"}
I am working with ASP.NET Core MVC. I have this connection string in my appsettings.json file but it doesn't seem to work. While running "dotnet ef database update" from cmd, I am getting this error keyword not supported: 'server.'. What's wrong with it?

Apologies! In my ConfigureServices method in Startup.cs, I was using SQLite database provider
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")))
I changed it to the following, and it worked with my connection string.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")))

The connection string should start of with Data Source=.
In Visual Studio if you open the SQL Server Object Explorer and click on the database you are wanting to connect to. The connection string will be displayed in the Properties window. The connections string should look something like this for localDb
Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=DbName;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=Fals

Related

Cannot drop database because it is currently in use MVC

I'm brand new to using MVC, and I'm trying to use an initializer to initialize data into my DB when the application is first started. Here is what I've got in Global.asax.cs:
System.Data.Entity.Database.SetInitializer(new MyAppInitializer());
MyAppContext db = new MyAppContext();
db.Database.Initialize(true);
In Web.config, here is my connection string:
<connectionStrings>
<add name="MyAppContext"
connectionString="data source= MyServer; Integrated Security=True; database=MyDatabase"
providerName="System.Data.SqlClient"/>
This is using MS SQL 2008 R2. My Initializer looks like this:
public class MyAppInitializer : DropCreateDatabaseAlways<MyAppContext>
{
protected override void Seed(MyAppContext context)
{
var organizations = new List<Organizations>
{
new Organizations { OrgName = "AT", OrgPhone = 5093333433, OrgOfficeLocation = "ITB", OrgPointOfContact = "Tony", OrgIsActive = 1 },
new Organizations { OrgName = "Libraries", OrgPhone = 5093331122, OrgOfficeLocation = "Holland-Terrell", OrgPointOfContact = "Herald", OrgIsActive = 1 }
};
organizations.ForEach(s => context.Organizations.Add(s));
context.SaveChanges();
I made sure I closed my connection to the server and database in SQL Server Management Studio, but multiple people have access to this DB, although none should be using it right now. How can I get it so I can initialize this data in my DB? Thanks!
Edit: I've already got the DB created on the server, but it is completely empty (no tables, procedures, etc). Would this cause an issue?
I faced a similar issue today when using MVC codefirst. After 20 mins of trying out various stuff I noticed that, the "Server Explorer" tab in Visual Studio had a connection open to my database. After I "closed" the connection in the server explorer tab of visual studio, the code was able to run and automatically recreate the database.
In SSMS run something like this...
USE master -- be sure that you're not on MYDB
ALTER DATABASE MYDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE MYDB;
As described by Vardhini... close DB connection in Server Explorer.
In the SSMS "Delete" window make sure that "Close existing connections" is checked.
Closing all existing connections of the database in visual studio server explorer and SQLManagement studio solved the problem for me.
My observations are:
Cannot be logged in to application
Cannot be connected to db with Server Explorer
Cannot be connected with SSMS
Then the application rebuild DB even when Database.SetInitializer<DbContext>(new DbInitializer()); is in public DbContext(); - NOT as other answears stand to put it into Application_Start();

Keyword not supported: 'data source'.: EF code-first using ObjectContext and LocalDB

I am getting a "keyword not supported error" when I try to connect to a LocalDB database using ObjectContext.
This is my connection string:
<add name="connStr" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=proj1db;Integrated Security=True" />
and this is the code that tries to create an instance of the ObjectContext:
var connectionString = ConfigurationManager
.ConnectionStrings["connStr"]
.ConnectionString;
ObjectContext _context = new ObjectContext(connectionString);
The last line throws System.ArgumentException: Keyword not supported: 'data source'.
I am using Visual Studio 2012 for Web and targeting .NET Framework 4.5. I have LocalDB installed on my machine.
If I use DbContext instead it works:
public class proj1dbContext: DbContext
{
public proj1dbContext() : base("name=connStr")
...
It seems that this is a similar question
Help with EF Code first connection string
but unfortunately it does not give a definitive answer to why instantiating ObjectContext throws that error.
Any help is appreaciated. Thanks!
ObjectContext takes an EF connection string (with Metadata and Provider Connection String keywords), not a provider-specific connection string.
You can't use ObjectContext with Code-First; ObjectContext requires the metadata XML files.

How do I connect to a local Microsoft Sql server 2012 Express database from a C# program?

Can someone please help me fix my connection string? I am an absolute beginner using the MS SQL Management Studio but I am an experienced C# programmer. I am trying to figure out how to connect to a local database on my PC. I just installed SQL server 2012 Express today and I created a table with one row of data. I am trying to access that table from a C# program. I've been looking for help calling a stored procedure (with no parameters) and it seems like I am doing everything right, but I get an exception error "Could not find stored procedure 'GetCustomers'." I have also tried changing my the procedure name to "dbo.GetCustomers" and also "SqlTest.dbo.GetCustomers" and also "SqlTest.GetCustomers", but nothing seems to work. Clearly I am not connecting to my database correctly. I've been working on this for 4 hours now so it's time for me to stop and find help. I think all I need is a good connection string and the proper syntax for the procedure.
Connect c = new Connect();
if(c.MakeConnection())
{
try
{
DataSet data = new DataSet();
SqlDataAdapter adaptor = new SqlDataAdapter();
//changed to use stored procedure
adaptor.SelectCommand = new SqlCommand("GetCustomers", c.MyConnect);
adaptor.SelectCommand.CommandType = CommandType.StoredProcedure;
//adaptor.SelectCommand.ExecuteNonQuery();//this throws an exception.
adaptor.Fill(data);//this throws an exception.
}
catch (Exception e)
{
Logger.WriteMessage(e.Message);
}
finally
{
c.CloseConnection();
}
My connection class contains the following:
string connection = Properties.Settings.Default.DatabaseConnectString;
sqlConnection = new SqlConnection(connection);
sqlConnection.Open();
Connection string I have tried which seem to connect OK:
Server=(localdb)\v11.0;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Integrated Security=true;
My Database name is SqlTest. I have tried several variations in my connection string, but most of them throw a logon failed exception error. I verified that my windows user ID has admin privileges for the database.
Connection strings I have tried which cive me logon errors:
Server=(localdb)\v11.0;Initial Catalog=SqlTest;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Initial Catalog=dbo;User ID=Raphael\couchpotato;Integrated Security=SSPI;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Trusted_Connection=Yes;
Server=(localdb)\v11.0;Database=SqlTest;Integrated Security=true;
I guess all I needed was some sleep. ;-)
I needed to set all of my SQL server services to Automatic. For some reason, they were set to manual, and so they were not started.
Then, I also needed to set the correct server name in my connection string. This is the same server name that is used to logon when starting SQL Server Management Studio. Here is a connection string that connects and accesses the correct database and table:
Server=RAPHAEL\SQLEXPRESS;Database=SqlTest;Trusted_Connection=Yes;

Dynamically Create DB Connection String for Entity in MVC 4

I have an entity in MVC 4 project and the connection string is placed in the web.config by the entity creation wizard.
I need to change this and assign the password to the connection string (which is stored outside the web.config) at run time.
How can I combine values outside the web.config with a string stored inside the web.config?
Or can I move the entity connection completely outside the web.config?
This is the existing entity connection string:
add name="MyEntities" connectionString="metadata=res://*/Models.NewUsers.csdl|res://*/Models.NewUsers.ssdl|res://*/Models.NewUsers.msl;provider=System.Data.SqlClient;provider connection string="data source=mydb;initial catalog=MyDatabase;persist security info=True;user id=sa;password=Mypassword;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
For 2, you can always pass a new connectionString (not from web.config) directly to the context when you create it:
string newCS = "add name=...";
var context = new MyEntities(newCS);
For 1, use EntityConnectionStringBuilder to parse an existing CS or build a new one.
A simple solution might be to use something based on:
string con = ConfigurationManager.ConnectionStrings["PerinatalDataEntities"].
ConnectionString;
con = con.replace("user id=sa", "user id=MyUser").
Replace("password=Mypassword","password=MyNewpassword")
I believe there is also a connection builder but I've never used it.

How to resolve database connection string problems in asp.net?

I am developing an asp.net mvc3 application using Visual Studio 2010.I need to access the database.
I wrote the connection string as
SqlConnection conn = new SqlConnection("Data Source=./App_Data/Abcd.mdf;Integrated Security=True;User Instance=True");
But, when I run the code, I get an error: 40 - Could not open a connection to SQL Server.
From the SQL Server Configuration Manager, I enabled TCP/IP but I still get the same exception.
I also tried changing the connection string to
SqlConnection conn = new SqlConnection("System.Configuration.ConfigurationManager.ConnectionStrings.ConnectionString");
But I got an exception that said "Format of the initialization string does not conform to specification starting at index 0."
How do I overcome this problem?
Thank you in advance for your help.
This will depend on the type of database you are using: SQL Express or SQL Developer/Standard. If you use SQL Express you may take a look at the following article illustrating different connection strings. For example:
Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Abcd.mdf;Integrated Security=True;User Instance=True
If you are using the full version of SQL Server, your database is no longer stored in the App_Data folder. It is managed by SQL Server. Checkout the following site for connection strings in this case depending on your scenario.
Example:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
SqlConnection conn = new SqlConnection("Data Source=.\sqlexpress;database=dbname;AttachDbFilename=|DataDirectory|\Abcd.mdf;Integrated Security=True;User Instance=True");
or
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("webconfigconnectionname").ConnectionString);
In VS click on server explorer and add the connection
when the connection has been setup right click on the established connection and select properties
you will get the properties window open. In that window select the connection string, which you can use in the sqlconnection

Resources