I am trying to run this code:
var db = Database.Open("DBNAME");
var q = "Select Name From Table";
#foreach(var row in db.Query(q)){
<li> #row.Name </li>
}
But I get the error System.InvalidOperationException: Connection string "DBNAME" was not found.
So I went in to WebMatrix 3 and added this database under Other Connections and working fine in the WebMatrix3 app. But the connection string I fed WebMatrix to add to the connections was not appended to the web.config file, and I still get this error, so not sure what else to do? Suggestions?
Also, do DB connections like this have to be closed? I did not see a close statement in the example I took this from, which is from here: http://www.w3schools.com/aspnet/webpages_database.asp
Update: I added the following setting in web.config:
<connectionStrings>
<add name="DBNAME" connectionString="server=(local)\Server;database=DBNAME;uid=myUser;password=myPass;" />
</connectionStrings>
And now I get the following error instead: System.ArgumentException: Keyword not supported: 'server'. <-- this error shows up for the #foreach line
You can just add the connection string to your web.config file. Depending on what kind of database you use.
If you use SQL Server you can use something like this:
<configuration>
<connectionStrings>
<add name="DBNAME" connectionString="Data Source=.\Server;Initial Catalog=MyDatabase;User ID=Username;Password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
<configuration>
More on connection strings here: http://www.connectionstrings.com/
Edit:
Yes Database connection should be closed! It implements IDisposable interface so you should use the using clause.
Here is an example
using (Database db = Database.Open("DBNAME"))
{
// Do your database stuff here
}
It will call the Dispose mehtod when it reaches the end of using clause. Dispose() will close the connection upon many other things.
Related
I have 3 types of connection strings in my webconfig, we use them for various parts of the application such as LDAP login, DB status of a related but non integrated DB, and the EF DB First connection strings (EDMX)
I am looking to parse the connection string data in the most economical way system wise. currently
<add name="ADConnectionString" connectionString="LDAP://something.somewhere.something:389" />
<add name="DEV" connectionString="data source=SOURCE;initial catalog=Test;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework;User ID=tech;Password=*********;" providerName="System.Data.SqlClient" />
<add name="ConfigEntities" connectionString="metadata=res://*/Data.Config.csdl|res://*/Data.Config.ssdl|res://*/Data.Config.msl;provider=System.Data.SqlClient;provider connection string="data source=SOURCE;initial catalog=CATALOG;persist security info=True;user id=user;password=*********;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
In order to process the connection strings I find I need to try catch two sections in order to complete the process
First the try catch allows us to skip LDAP connection string safely (which should be skipped without the try catch
second it seems I need to cast the strings to retrieve the data from them...
try
{
var ssb = new SqlConnectionStringBuilder((((ConnectionStringSettings)c).ConnectionString));
}
vs
try{
var ssb = new SqlConnectionStringBuilder((new EntityConnectionStringBuilder(((ConnectionStringSettings)c).ConnectionString).ProviderConnectionString));
}
from there the code is identical
does anyone have thoughts on the best way to determin the type of connection string prior to running the code to prevent the need to rely on try catches.
You can get the name property of the connection string from ConnectionStringSettings. Use name property to identify the type of connection string.
You already have ConnectionStringSettings object, which is c (based on your code snippets).
Check for the name property as shown below to avoid try statement.
if(c.Name.Equals("ADConnectionString")) //ADConnectionString
{
}
else if(c.Name.Equals("DEV")) //DEV
{
}
else //ConfigEntities
{
}
SHORT VERSION: Is it possible and how to define a variable in a web.config file that I can use within itself.
I am new to a company and also a beginner developer in C# MVC Web applications. I have been tasked to maintain and test a web application that has multiple connections strings in a single web.config file. These connection strings, however, have the same values in it like:
<connectionStrings>
<add name="DefaultConnection" connectionString="provider=System.Data.SqlClient;provider connection string="data source=SUPERCOMPUTER\SQLEXPRESS2012;initial catalog=HumanResourceDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DefaultConnection3" connectionString="Data Source=SUPERCOMPUTER\SQLEXPRESS2012;Initial Catalog=HumanResourceDB;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
As you can see, the difference with these two is just the Name of the connection. Since Im a beginner I don't exactly know why this application has to use 2 same connection strings with different names. I was told that one is being used by Database First entity framework and the other is being used by ASP.NET Identity Code First and I do not know right now what those are.
The problem: I am CONSTANTLY changing connection strings value to test with different machines/environment/database etc and the need to modify 2 connection strings is really slowing me down.
The question: Is it possible to use variables that I can just declare at the top of the web config file and use it in the connection strings so that I can just modify the variable values. Something like this:
var Server = SUPERCOMPUTER\SQLEXPRESS2012
var IntegratedSecurity = true
var database = HumanResourceDB
var user = databaseusername
var password = databasepassword
<connectionStrings>
<add name="DefaultConnection" connectionString="... data source=**Server**;initial catalog=**database**;integrated security=**IntegratedSecurity **;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DefaultConnection3" connectionString="Data Source=**Server**;Initial Catalog=**database**;Integrated Security=**IntegratedSecurity**" providerName="System.Data.SqlClient" />
</connectionStrings>
Additional Question: Is it really impossible to use one connection string if the mvc application relies on both Database First Entity Framework and Code First .NET Identity?
All EF project have a dbContext File..so you can use multiple EF projects(Code First, DB first) in just one solution.
Yes its clearly possible ...in code first your db context can get the name of each ConnectionString you want!.. like this:
public class AppContext : DbContext
{
public AppContext() : base("ConString Name")
{
}
}
so you can change the connection string name to another one..like DefaultConnectionString1 to DefaultConnectionString12 or 1000 ...
and you can have multiple db context to work on multiple databases to...
in Code first from database is like that to ...so in each part of project you can make instanse of which dbcontext you like. and do CRUD operation on that..
I have create MVC5 application and I have local DB ,currently I have entered data
to the table and I able to see that in the MDF file under server explorer ->data connections ,now I want to read it via API below and its not working i've provided the ID which I have in the table and I get null ,I think maybe that I need to provide the connection string to the API but not sure how ,any idea how to do that?
This is DB context from the model definition
public class PersonModelDbContext : DbContext
{
public PersonModelDbContext()
: base("Connection1")
{
}
This is the read API
private PersonModelDbContext db = new PersonModelDbContext();
public Person GetPrviderData(string id)
{
Person person = db.Person.Find(id);
return person;
}
This is the connection string in the WEB CONFIG FILE
<connectionStrings>
<add name="Connection1" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Person.mdf;Initial Catalog=Persons;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Update - in addition I try with the following without success ,I got error:
db.Database.Connection.ConnectionString = #"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Person.mdf;Initial Catalog=Persons;Integrated Security=True";
An exception of type 'System.Data.DataException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: An exception occurred while initializing the
database. See the InnerException for details.
You could try setting your connection string to more this format since it is local
<add name="DataBaseConnectionName"
connectionString="Data Source=[ServerNameHere];User ID=[DatabaseLogonID/Probably sa];Password=[DatabasePassword];Initial Catalog=TheNameoftheLocalDB;"
providerName="System.Data.SqlClient" />
You could try that to establish a connection also don't keep the [brackets] in the connection string.
ask your advices about this:
I am trying to create db compact edition,
first time it was successfully with default dbName (ProjectName.dbContextName).
But i decided to define my own name, and added in app.config in connectionString sections my connection string. After db was not created.
From here MSDN Use code first with connection by convention i have done similar connection string:
<connectionStrings>
<add name="TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
(section name is equal to my dbcontext's name class.)
Just to be sure before dbContext will be created:
Database.SetInitializer(new DropCreateDatabaseAlways<TestContext>());
Db still is not created. What am i doing wrong? Thanks in advance.
VahidN, i tried to add call of base class constructor, but doesn't work. Don't understand. It should be very easy. And as were aforementionted in ref above, if name of connection string in config section and name dbContext class are equal - object finds its connection string without problems.
Well, debugger says that conString is defined correctly (equal to string in config section), but actually db is not created - i can't find it nor in appfolder nor in sql server folders.
You need to include the full namespace in the name of the connection-string. See here.
Something like this
<connectionStrings>
<add name="YourNameSpace.TestContext"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=TestDb.sdf;"/>
</connectionStrings>
Oh, sorry me for giving insufficient information, db was not created cause entities in dbContext was defined as List, not dbSet. inadvertency (
What does this error mean?
Format of the initialization string does not conform to specification starting at index 0.
and also getting this error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I'm trying to use my EF model context in another project in Visual Studio. Having real trouble just getting my EF application off the ground.
I instantiate the model context like so:
ctx = new VisitoriDataModel("VisitoriDataModel");
I have the connection string copied from the data layer project into all projects including the web.config and still no luck.
Also tried the following:
//model = new VisitoriDataModel(new EntityConnection("Name=VisitoriDataModel"));
//model = new VisitoriDataModel("Name=VisitoriDataModel");
//model = new VisitoriDataModel("VisitoriDataModel");
//model = new VisitoriDataModel();
ConnectionString is like so:
metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"
The connection string needs to go in the project that is being executed. If this is a website, that would be the web.config. Make sure it's correctly nested, and not inside another node like <system.web>, you should have:
<configuration>
...
<connectionStrings>
<add name="VisitoriDataModel" connectionString="metadata=res://*/Context.VisitoriDataModel.csdl|res://*/Context.VisitoriDataModel.ssdl|res://*/Context.VisitoriDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=visitori;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
...
</configuration>
Also note that the "'s around the provider connection string inside the entity connection string need to be escaped as "