Entity SQLCE Can't find connection string in app.config file - vb.net

I've been getting this error when I try and use my model container:
No connection string named 'PFModelContainer' could be found in the
application config file.
I have my edmx file in a separate project. I checked the app.config file and my model was there, and I also put it in my main project app.config file. Still doesn't work. Here's the connection string:
<connectionStrings>
<add name="PFModelContainer"
connectionString="metadata=res://*/PFModel.csdl|res:
//*/PFModel.ssdl|res://*/PFModel.msl;
provider=System.Data.SqlServerCe.3.5;
provider connection string="
Data Source=C:\Documents and Settings\Jon\My Documents\Visual
Studio 2010\Projects\SpreadsheetAddIn
\SpreadsheetAddIn\bin\Debug\PFData.sdf;
Password=password""
providerName="System.Data.EntityClient" />
</connectionStrings>
Here's how the context is called:
Private mdbContext As New PFModelContainer
Which goes to:
Partial Public Class PFModelContainer
Inherits DbContext
Public Sub New()
MyBase.New("name=PFModelContainer")
End Sub
I thought the answer would be similar to what happened to this guy. But unfortunately his solution doesn't work with mine.
Update:
I've noticed the error isn't caught until I hit this code. It occurs when I do the linq query on the third line.
Dim dbContext As New PFModelContainer
Dim dbAccount As IQueryable(Of Account)
dbAccount = From a In dbContext.Accounts
Where (a.AccountName = "Hello")
Select a
Update (What I've tried for connection strings - that I can remember):
1 Main Project: --> Default Creation
<add name="PFModelContainer"
connectionString="metadata=res://*/PFModel.csdl|
res://*/PFModel.ssdl|
res://*/PFModel.msl;
provider=System.Data.SqlServerCe.3.5;
provider connection string="
Data Source=C:\Documents and Settings\Jon\My Documents\Visual Studio 2010\Projects\SpreadsheetAddIn\PFDatabase\bin\Debug\PFData.sdf;
Password=password""
providerName="System.Data.EntityClient" />
Library:
<add name="PFModelContainer"
connectionString="metadata=res://*/PFModel.csdl|
res://*/PFModel.ssdl|
res://*/PFModel.msl;
provider=System.Data.SqlServerCe.3.5;
provider connection string="
Data Source=|DataDirectory|\bin\Debug\PFData.sdf;
Password=password""
providerName="System.Data.EntityClient" />
2 Main Project: --> Replace * with PFDatabase
<add name="PFModelContainer"
connectionString="metadata=res://PFDatabase/PFModel.csdl|
res://PFDatabase/PFModel.ssdl|
res://PFDatabase/PFModel.msl;
[...Same...]
Library:
[...Same w/ modifications...]
3 Main Project: --> Replace res://*/ with .\
<add name="PFModelContainer"
connectionString="metadata=.\PFModel.csdl|
.\PFModel.ssdl|
.\PFModel.msl;
[...Same...]
Library:
[...Same w/ modifications...]
4 Main Project: --> Replace res://*/ with ~\
<add name="PFModelContainer"
connectionString="metadata=~\PFModel.csdl|
~\PFModel.ssdl|
~\PFModel.msl;
[...Same...]
Library:
[...Same w/ modifications...]

If you are placing your edmx model in a separate class library, add an app.config to that class library and add the connection string to that config.
Additionally, if your datamodel resides inside a namespace then you will have to include the full namespace in your resource path:
For example, if you placed your edmx file in an assembly called MyProject.DataLayer and the namespace for the generated code is MyProject.DataLayer.DataModel, then your configuration string should be:
<add name="PFModelContainer"
connectionString="metadata=res://*/DataModel.PFModel.csdl|res:
//*/DataModel.PFModel.ssdl|res://*/DataModel.PFModel.msl;
provider=System.Data.SqlServerCe.3.5;
provider connection string="
Data Source=C:\Documents and Settings\Jon\My Documents\Visual
Studio 2010\Projects\SpreadsheetAddIn
\SpreadsheetAddIn\bin\Debug\PFData.sdf;
Password=password""
providerName="System.Data.EntityClient" />

Got some help from experts exchange on this one. Ended up doing a work around (not sure why it wasn't working like it should), since I'm using DbContext instead of EntityObject I had to create my own overrideable procedure like (the second one below):
Public Sub New()
MyBase.New("name=PFModelContainer")
End Sub
Public Sub New(ByVal connectionString As String)
MyBase.New(connectionString)
End Sub
I then had to create my own connection string, which is basically what the original code generated, so, I'm not sure why it wasn't working from the app.config file. Maybe there's a bug in the program that will be fixed the next go around? Hopefully that was it, either that or I did something wrong, mystery.

Related

How to specify a database when using InitializeDatabaseConnection()

I am working with the default Internet template when using MVC 4.0. How can I specify where the initial database is created? I have installed SQL Server Express 2012 and want the database created there instead of in the Visual Studio built-in SQL Server.
I did try using the default and then copying the database from VS to SQL Express 2012 but I don't seem to be able to back up the VS database.
Anyone have any idea?
Thanks, Mark
You need to add a connection string in the config which has a name matching the name of your context class, for example:
<connectionStrings>
<add name="FooBarContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=FooBar;Integrated Security=SSPI;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
In the above, my context class is named FooBarContext which matches the connection string name. The context class looks something like this:
public class FooBarContext : DbContext
{
// etc.
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "Users", "Id", "Login", autoCreateTables: true);
where DefaultConnection — connection name in your web.config (in <connectionStrings>)

Invalid value for key attachdbfilename after renaming connectionString

I am building the sample MvcMovie tutorial for ASP.NET MVC 4. I'm using EntityFramework Code First features and created a connectionString as follows.
<add name="MoveDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDictionary|\Movies2.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
Everything worked fine at this point. But then I realized that I named my connection string MoveDBContext instead of MovieDBContext and, being the perfectionist I renamed it. After doing this I now receive an error in my MoviesController/Index method.
public class MoviesController : Controller
{
private MovieDBContext db = new MovieDBContext();
public ActionResult Index()
{
return View(db.Movies.ToList()); // Error: Invalid value for key 'attachdbfilename'
}
...
}
If I change the name back to MoveDBContext the error goes away.
Can anyone tell me where this original name is being referenced?
EF, by default, looks for a connection string with the same name as the type that extends DbContext.
Or, better put by Scott:
By default, when you create a DbContext class with EF code-first, it
will look for a connection-string that matches the name of the
context-class. Since we named our context class “NerdDinners”, it
will by default look for and use the above “NerdDinners” database
connection-string when it is instantiated within our ASP.NET
application.
Edit:
After looking closer, I think your connection string is the problem. You've got DataDictionary instead of DataDirectory. Try this (line feeds added for readability):
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\Movies.mdf;
Integrated Security=True"
providerName="System.Data.SqlClient" />
Apparently, as Ken said, the MoveDBContext was not being referenced.
I removed the entire connectionString from the web.config and everything still functioned correctly.
So, it still begs the question, "How did Visual Studio know to create a database in my SQLExpress instance?" and "Where is that configured at?"

SimpleMembershipInitializer won't initialize

I am struggling with getting a simplemembership scenario working in my EntityFramework / MVC4 / DatabaseFirst project. I've found plenty of examples for working with code first, but nothing for DB first.
The problem I'm encountering is the the InitializeDatabaseConnection is throwing an error ("Unable to find the requested .Net Framework Data Provider. It may not be installed.") The code looks like this :
WebSecurity.InitializeDatabaseConnection("DALEntities", "tblContacts1", "ContactID", "EMail", autoCreateTables: true);
I am not sure what DataProvider is failing. If I try to trace 'into' the InitializeDatabaseConnection call, it immediately throws the error.
What am I missing?
Info:
DALEntities is the name of the connectionString that the rest of EF uses. The following code works just fine....
public ActionResult Test() {
using (var db = new DALEntities()) {
var query = from i in db.TBLINVENTORies
orderby i.ITEMNAME
select i;
var cnt = query.Count();
string str = "Total Inventory: " + cnt;
return Content(str);
}
}
My connection strings section from the web.config:
<connectionStrings>
<add name="DALEntities" connectionString="metadata=res://*/DAL.DAL.csdl|res://*/DAL.DAL.ssdl|res://*/DAL.DAL.msl;provider=System.Data.SqlClient;provider connection string="data source=SOMECOMPUTER;initial catalog=SOMEDB;persist security info=True;user id=SOMEID;password=SOMEPASS;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
This post seems to be asking the same question (but in context of model-first), but there is no solution yet : Using SimpleMembership with EF model-first
Also, I see that there is an overload for WebSecurity.InitializeDatabaseConnection() with the help text: Initializes the membership system ((blah blah <snip> ProviderName: the name of the ADO.NET data provider. If you want to use Microsoft SQL Server, the WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String, String, String, String, Boolean) overload is recommended . I do wish to connect to a MSSQL server...will this be required?
The provider giving you trouble is the one specified in your connection string which is System.Data.EntityClient. I suspect the problem is because your project is database-first whereas the simple membership is using code-first. I do not think you can mix these approaches in a single database. Try putting it back to where the DefaultConnection is used for IntializeDatabaseConnection. There should have been a DefaultConnection in your web.config generated by the MVC4 scaffolding. This connection string usually uses System.Data.SqlClient as the provider.
If you want to keep the simple membership in the database used to store domain information (i.e. DALEntities) then you will need to change your method for using EF on the domain to code-first. If you want to keep your project database-first you need to design your own membership schema in the database and develop custom member and role providers. This is probably the best approach if you are really trying to integrate user information into your domain model.
For simplicity and clarity keep two connection strings pointing to the same database. One for EF (doesn't matter if code first or data first) and one for your WebSecurity stuff. (As Chad and Erik said)
<add name="DataEntities" connectionString="metadata=res://*/Models.DataEntities.csdl|res://*/Models.DataEntities.ssdl|res://*/Models.DataEntities.msl;provider=System.Data.SqlClient;provider connection string='data source=[YOUR_SERVER];initial catalog=[YOUR_DATABASE];integrated security=True;MultipleActiveResultSets=True;App=[YOUR_APP_NAME]'" providerName="System.Data.EntityClient" />
<add name="DataDB" connectionString="data source=[YOUR_SERVER];initial catalog=[YOUR_DATABASE];integrated security=True;MultipleActiveResultSets=True;App=[YOUR_APP_NAME]" providerName="System.Data.SqlClient" />
Note that the providers are different: EF uses System.data.EntityClient and non-EF one uses System.Data.SqlClient.

Using appsettings, but "ConfigurationSettings" method is obsolete

I've trying to access an appsettings key value in my vb.net 2.0 web application.
I've put the key in the app.config file:
<appSettings>
<add key="DownloadURL" value="http://<myURL>/" />
</appSettings>
I've followed the instructions here, and it says that I need to access this key like so:
URL = System.Configuration.ConfigurationSettings.AppSettings("DownloadURL")
But I get the following message:
Public Shared Readonly property
AppSettings() As
'System.Collections.Specialized.NameValueCollection'
is obsolete: 'This method is obsolete,
it has been replaced by
System.configuration!System.configuration.configurationmanager.AppSettings'
I tried to replace the old method with the new one, but it does not exist.
Strange, since I've done a similar thing with a web app and it did exist there.
Add a reference to System.Configuration.dll.
Here's an explanation.

how to vb.net programmatically specify connection string in dataset.xsd in vs2005

I want to create a dataset.xsd in vs2005, and I am using access database, so I cant know where my client save the application. Hence I used application.startuppath() to get the application folder and appended "Data\db.msd" to the application.startuppath() so i got the target location for the access databse in client machine. Now to create crystal reports I need the dataset.xsd but while creating a new dataset.xsd it was asking the path for the access database, how to programmatically specify the connection string in dataset.xsd so that i can create a connection string. and use that dataset for creating crystal reports.
Thanks in advance
Is it possible that the connection is only used to get the schema of the dataset.
Will you be filling the dataset using a DataReader?
If so i dont think the connection to the dataset is important, it is only to get the schema. You can create the dataset amnually, if it not to mutch effort, and populate it using the appropriate data reader.
You can use AppSettings to store the connection string and retrieve it at runtime. You can then store the connection string information under configuration -> connectionStrings and retrieve it from the application. You could then modify the connection string without having to modify the code.
Your app.settings would look like this (simplified) and replace the ****** with your own connection string:
<configuration>
<connectionStrings>
<add connectionString ="******" name="AccessConnectionString"/>
</connectionStrings>
<appSettings>
</appSettings>
</configuration>
Dim AccessConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings.Item("AccessConnectionString").ConnectionString
theConnectionObject.ConnectionString = AccessConnectionString
theDataAdapter.Fill(theDataSet)